Including files and using arrays

by Andres Baravalle

Week 3: Including files and using arrays

  • Including files
  • Using arrays
  • Looping arrays

Including files

Require & Include

PHP provides 2 different ways to include existing content into the current files:

  • include/include_once
  • require/require_once

Including existing content is useful for reusing content. It allows to better structure your applications and organise your code in different files across different folders (e.g. having a folder for external libraries, classes and templates).

You can then incorporate that content as needed, keeping each of your files leaner & cleaner.

Require & Include (2)

You will normally use include/require or include_once/require_once to:

  • Include any external libraries
  • Include footers, headers, navigation bars etc.

You can include/require local files or remote resources.

include/include_once

The include statement includes and evaluates the specified file. You can include content at any point in your code and it will inherit the variable scope of the line in which it was included.

Include statements can be used to import libraries, classes or simply to use common headers and footers.

When using include_once, a file that was already included will not be included again. This is useful when the same file might be included by different parts of the code (e.g. a class required by different components).

<?php
include "footer.php";
include "http://www.example.com/footer.php";
include_once "classes/class1.php";
?>

require/require_once

require and require_once statements are very similar to include/include_once, the main difference being that execution will halt throwing a fatal error if the file cannot be included.

Including content example

<!doctype html>
<html>
	<head>
		<?php include_once "includes/head.php";
	</head>
	<body>
		<section>
			<?php include_once "includes/header.php";
			// page content goes here
			<?php include_once "includes/footer.php";
		</section>
	</body>
</html>

include/include_once/require/require_once?

Which one to use?

Activity #1: Including existing content

Read the PHP documentation and create a simple web page and use one of the previous statements to add a footer to the page. The footer should include:

  • Some basic copyright information (e.g. Copyright © 2013 Andres Baravalle)
  • Your contact details (e.g. telephone and/or skype and/or Google Talk and/or LinkedIn and/or Facebook etc.)

Performance notes

PHP processing is slower than HTML serving. Including files further increases the time per request.

Request Time per request
Hello word in HTML 0.310 ms
Hello world in HTML + echo "Hello World" in PHP 0.465 ms (+50%)
Hello world in HTML + echo "Hello World" in PHP + including footer 0.533 ms (+71%)

Measured on a Xeon 2.40Mhz/2GB vm, using Apache ab over 100 requests.

Using arrays

What are arrays?

Arrays are a data structure found in most programming languages and typically used to store a number of related items.

In PHP, arrays have values which are stored in given positions (keys).

key 0 1 2 3
value 20 50 75 100

The table above is a visual representation of an array, represents the number of votes in an election for four different candidates. The numbers 0, 1, 2 and 3 are the keys (each key representing a candidate).

Creating arrays: implicit keys

The previous arrays might have been created using the array() function:


<?php
$array = array (20, 50, 75, 100);
?>                 

Array keys and values

Array keys can be integers (as in the previous example) or strings:

key Andres Mike Gaurav Paolo
value 20 50 75 100

When using integers, you do not need to use consecutive keys.

You can store any type of value in an array.

Creating arrays: int keys

The previous arrays might have been created using the array() function, specifying the keys (0, 1, 2 and 3):

<?php
$array = array(
	0 => 20,
	1 => 50,
	2 => 75,
	3 => 100
);
?>          

Creating arrays: string keys

<?php
$array = array(
	"Andres" => 20,
	"Mike" => 50,
	"Gaurav" => 75,
	"Paolo" => 100
);
?>          

You can mix string and int keys - although normally it is not recommended.

Creating arrays: square brackets syntax

Arrays can be also populated using the square brackets syntax:

$array[0] = 20;
$array[1] = 50;

You can do the same with string indexes:

$array["Gaurav"] = 75;
$array["Paolo"] = 100;

Creating arrays: square brackets syntax, implicit key

New elements can be added without including the key:

$array[] = 120; 

PHP will add the value at the end of the array and a numeric key will be generated automatically (starting with 0, or after the highest key number used in the array).

Accessing values

  • Use square brackets to refer to specif array elements (e.g. $a[0])
  • You can also use print_r() or var_dump() to print information on a variable
<?php
print_r($array);
var_dump($array); 
echo $array[0];
?>

var_dump($array)

var_dump

Activity #2: Write your first array

Create an array listing these adjectives describing people: righteous, selfish, evil, blessed, weak.

Replace those adjectives in the text below (Ezekiel 25:17) with elements of your array and print the text:

The path of the righteous man is beset on all sides by the inequities of the selfish and the tyranny of evil men. Blessed is he who, in the name of charity and good will, shepherds the weak through the valley of the darkness, for he is truly his brother's keeper and the finder of lost children.

Variables as keys

You can also use variables (as long as their value is a string or an int) as keys:

$key = "Andres";
$array[$key] = 20;

Looping arrays

Looping integer keys

One very common way of using an array involves using a for loop to access every element (or a range of elements), as the loop's number can be used as the array element number.

The code below prints out every element of an array using consecutive integer keys:

<?php
for ($key = 0; $key < sizeof($array); $key++) {
	echo "$key: " . $array[$key] . "\n"; 
}
?>

Looping with foreach()

You will notice how the code in the previous slide does not work with all the array we have created before.

This is because in some of the arrays, we have been using strings as keys. To loop through a generic associative array, you need to use a different construct, foreach:

foreach ($array as $key => $val) {
	echo "$key: $val\n"; 	
} 

foreach iterates ("walks") through the elements of an array; on each iteration:

  1. The value of the current element is assigned to $val 
  2. The internal array pointer is advanced by one position
  3. Anything in the body of the construct is executed

Looping with foreach() (example)

<?php
$array = array(
	"Andres" => 20,
	"Mike" => 50,
	"Gaurav" => 75,
	"Paolo" => 100
); 

$count = 0;

foreach ($array as $key => $val) {
	echo "$key: $val\n";
}
?>           

Looping with foreach() (example, output)


Andres: 20
Mike: 50
Gaurav: 75
Paolo: 100
              

Looping with while... each

You can also use a while... each loop to transverse arrays:


reset($array); 

while ($element = each($array)) {
	echo $element["key"] . ": " . $element["value"];
}

each() explained

The each() construct returns the current element in an array and moves the internal pointer to the next one.

The current element is returned as an array; it's a bit of a tongue twister, but:

  • the "key" key will have as value the key of the current element
  • the "value" key will have as value the value of the current element
  • two numeric keys will be also created:
    • 0, will have as value the value of the current key
    • 1, will have as value the key of the current element

When the internal pointer for the array points past the end of the array contents, each() returns false (hence the loop ends).

each() demonstrated


<?php
$array = array(
        "Andres" => 20,
        "Mike" => 50,
        "Gaurav" => 75,
        "Paolo" => 100
);

print_r(each($array));
?>

// result :
// Array (
// [1] => 20
// [value] => 20
// [0] => Andres
// [key] => Andres
// )  
?>         

while... each() demonstrated


while ($element = each($array)) {
	// the table in the next page shows the value of $element during each iteration
}    
            

while... each() demonstrated

First iteration Second iteration
// element :
// Array (
// [1] => 20
// [value] => 20
// [0] => Andres
// [key] => Andres
// ) 
// result :
// Array (
// [1] => 50
// [value] => 50
// [0] => Mike
// [key] => Mike
// ) 
Third iteration Fourth iteration
// result :
// Array (
// [1] => 75
// [value] => 75
// [0] => Gaurav
// [key] => Gaurav
// ) 
// result :
// Array (
// [1] => 100
// [value] => 100
// [0] => Paolo
// [key] => Paolo
// ) 

Looping with while... list... each

You can also use a while... list... each loop to transverse arrays:


<?php
// remember to reset the pointer
// before transversing the same array twice!
reset($array); 

while (list ($key, $val) = each($array)) {
	echo "$key: $val\n"; 	
}
?>

The while... list... each loop is the most common way to transverse an array.

list() explained

In each iteration, the each() function returns the current element (as an array, having 1, value, 0 and key as indexes - see previous slides).

The list() function:

  • Takes the numerical indexes (0 and 1) and their values ("Andres" and 20, on the first iteration)
  • Assigns them to the variables $key and $val (you can use any name - it's the position that it's relevant, not the name).

Refer to the PHP documentation for more detailed info.

Looping with while... list... each (2)

If you do not need the key of an array element, just the value, you can use list() omitting the first parameter.


<?php
// remember to reset the pointer
// before transversing the same array twice!
reset($array); 

while (list (, $val) = each($array)) {
	echo "$val\n"; 	
}
?>        

Activity #3: Tarantino's movies

Retrieve the list of Quentin Tarantino's movies from his Wikipedia page and create an associative array of his movies. Use the year of release as key and output a list like this:

  • 1992: Reservoir Dogs
  • 1994: Pulp fiction
  • etc

Repeat the activity using more than one method to traverse arrays.

Multi-dimensional arrays

Each value in an array can be another array - that creates arrays or arrays. For example we may want to store information on music albums (e.g. as part of a records store software):

Id Artist Album Year
SKU1 Pink Floyd The Dark Side of The Moon 1973
SKU2 Pink Floyd Wish you Were Here 1975
SKU3 The Doors The Doors 1967
SKU4 Blowing in the Wind Bob Dylan 1973

Multi-dimensional arrays (example)

<?php
$array["SKU1"] = array("Pink Floyd", "The Dark Side of The Moon", 1973);
$array["SKU2"] = array("Pink Floyd", "Wish you Were Here", 1975);
$array["SKU3"] = array("The Doors", "The Doors", 1967);
$array["SKU4"] = array("Bob Dylan", "Blowing in the Wind", 1973);
?>

Multi-dimensional arrays (example 2)

<?php
$array2 = array(
	"SKU1" => array("Pink Floyd", "The Dark Side of The Moon", 1973),
	"SKU2" => array("Pink Floyd", "Wish you Were Here", 1975),
	"SKU3" => array("The Doors", "The Doors", 1967),
	"SKU4" => array("Bob Dylan", "Blowing in the Wind", 1973)
);
?>

Activity #4: arrays of arrays

The implementation in Activity #3 is far from ideal - e.g. it would be problematic if there would be more than one Tarantino movie per year.

Read on multi-dimensional arrays in the PHP documentation and rewrite activity #3 to create a 2 dimension array as per this outline:

Use the array to print a list as in activity #3 - but link the title of the movie to its Wikipedia page.

Array functions

A large number of functions exist to manipulate arrays. You will find useful to familiarise yourself to at least these ones:

array_diff() difference between two arrays
array_merge() join of two arrays
array_rand() Pick one or more random entries out of an array
array_search() Searches the array for a given value and returns the corresponding key if successful
sort() sorts an array
sizeof() returns the size of the array
extract() converts an array to scalar, using the keys as variable names
reset() resets the point in an array

Activity #5: using array functions

Use Google to find tomorrow's minimum and maximum temperature in 10 towns in UK and:

  • Store the temperature in an associative multi-dimensional array, using the city's name as key
  • Use a loop to display the temperatures in a web page
  • Sort the results by town name (you will need to use ksort()).

This work

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License

Creative Commons License