by Andres Baravalle
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.
You will normally use include/require
or include_once/require_once
to:
You can include/require local files or remote resources.
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
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.
<!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>
Which one to use?
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:
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.
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).
The previous arrays might have been created using the array()
function:
<?php
$array = array (20, 50, 75, 100);
?>
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.
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
);
?>
<?php
$array = array(
"Andres" => 20,
"Mike" => 50,
"Gaurav" => 75,
"Paolo" => 100
);
?>
You can mix string and int keys - although normally it is not recommended.
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;
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).
$a[0]
)print_r()
or var_dump()
to print information on a variable<?php
print_r($array);
var_dump($array);
echo $array[0];
?>
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.
You can also use variables (as long as their value is a string or an int) as keys:
$key = "Andres";
$array[$key] = 20;
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";
}
?>
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:
<?php
$array = array(
"Andres" => 20,
"Mike" => 50,
"Gaurav" => 75,
"Paolo" => 100
);
$count = 0;
foreach ($array as $key => $val) {
echo "$key: $val\n";
}
?>
Andres: 20
Mike: 50
Gaurav: 75
Paolo: 100
You can also use a while... each
loop to transverse arrays:
reset($array);
while ($element = each($array)) {
echo $element["key"] . ": " . $element["value"];
}
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:
When the internal pointer for the array points past the end of the array contents, each()
returns false (hence the loop ends).
<?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 ($element = each($array)) {
// the table in the next page shows the value of $element during each iteration
}
First iteration | Second iteration |
---|---|
|
|
Third iteration | Fourth iteration |
|
|
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.
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:
$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.
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";
}
?>
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:
Repeat the activity using more than one method to traverse 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 |
<?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);
?>
<?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)
);
?>
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.
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 |
Use Google to find tomorrow's minimum and maximum temperature in 10 towns in UK and:
ksort()
).This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License