Author: | |
Website: | |
Page title: | |
URL: | |
Published: | |
Last revised: | |
Accessed: |
A PHP array is a dynamic data structure that can hold multiple values of any datatype, including other arrays, in a single array variable with its own unique identifier. Each variable stored in an array is called an array element. A PHP array can best be described as an ordered map in which each array element consists of a key-value pair, and array elements remain in the order in which they are inserted.
Unlike programming languages such as C or C++, PHP does not need to store an array in a contiguous block of memory and uses a hash table-like structure, although it does pre-allocate extra memory to an array to allow for growth. This means it can be dynamically resized and employ mixed key types.
This flexibility comes at a price, however. The hash table-like structure means that PHP arrays consume significantly more memory than the fixed-length static arrays found in languages like C and C++. While this might not be a critical factor for small datasets, it will start to have consequences for performance as the size of the dataset grows.
We use arrays because they provide us with a convenient and flexible way to store and manipulate large collections of data, as opposed to having a potentially very large number of separate variables. Arrays allow us to model data structures such as lists, queues, stacks and hash tables. In fact, because the elements of an array variable can themselves be array variables, we can also use arrays to model more complex data structures like tables, trees and graphs.
In PHP, there are three distinct kinds of array:
We stated earlier that each array element in a PHP array consists of a key-value pair, which seems to contradict the notion of a numerically indexed array. In fact, the only difference between associative arrays and indexed arrays in PHP is that the key in an indexed array is an integer value, whereas the key in an associative array is (usually) the name of a variable. For indexed arrays, indexing starts with 0 by default (although bear in mind that as of version 8.0, PHP allows the use of negative index values).
We tend to use indexed arrays for homogeneous collections of data in which the array elements are all of the same datatype (e.g. all numbers, or all strings) and the ordering of the elements is important. This might be the case, for example, if we are modelling structures such as queues or stacks and want to implement LIFO or FIFO behaviour, or if we are storing a simple collection of string or numeric variables that don't require descriptive keys.
For an indexed array, indexing is performed automatically. When you create an array, the first element has an array index of 0, the second an array index of 1, and so on. Note that it is possible to have gaps in the array indexing, although this is not recommended as it can affect array handling performance.
Associative arrays contain collections of key-value pairs in which the stored values can have any datatype and the keys, each of which must be unique, are typically descriptive names stored as strings, although a key can also be an integer value. Associative arrays are object-like structures that are useful for storing a collection of named properties - for example, the key-value pairs found in a typical software configuration file.
Multi-dimensional arrays, as mentioned above, are arrays that contain other arrays, which in turn can contain other arrays . . . and so on. There are no restrictions on mixing array types within a multi-dimensional array, which means that multi-dimensional arrays can be used to model just about any kind of complex data structure. For example, an array is often used to store the contents of a database table.
In this article we will be looking at the ways in which the different kinds of array described above can be created, updated and manipulated. We will investigate the operators that can be used with arrays, including the union operator, and we will introduce some the more frequently used built-in functions provided by PHP for working with arrays (a comprehensive list of PHP's array functions can be found on the PHP Group's website here).
There are two main ways in which a PHP array may be created. The first method we will describe here requires the use of PHP's array() function. Let's suppose for the moment that we want to create an indexed array to hold the first five prime numbers. We could do something like this:
<?php
$primes = array(2, 3, 5, 7, 11);
var_dump($primes);
// array(5) { [0]=> int(2) [1]=> int(3) [2]=> int(5) [3]=> int(7) [4]=> int(11) }
?>
The array() function takes as its argument a comma-separated list of values. For an indexed array, we don't need to specify the index numbers for each array element because PHP will do this for us. As you can see, when the var-dump() function is applied to $primes, it outputs the variable type (array) followed by the number of elements in the array in parentheses (5), followed by a list of array elements enclosed within curly braces. Here is the first element in the list:
[0]=> int(2)
The number inside the square brackets is the index number of the element (0). The index number is followed by the key-value separator (=>), then comes the datatype of the element (int), and finally the value of the element (2) in parentheses. The var-dump() function is particularly useful when we want to know the datatype of a variable as well as its value. When used with an array variable it will also give us a breakdown of the individual array elements, including the index number or key, datatype, and value.
We'll now create the same array of prime numbers, again using the array() function, but this time explicitly specifying the index numbers to be used rather than relying on PHP to provide them for us:
<?php
$primes = array(0=>2, 1=>3, 2=>5, 3=>7, 4=>11);
var_dump($primes);
// array(5) { [0]=> int(2) [1]=> int(3) [2]=> int(5) [3]=> int(7) [4]=> int(11) }
?>
As you can see, the output is exactly the same as before, because we have used the same values for the array element indices as PHP would use by default. We could however do something rather different. For example, this is what happens when we leave gaps between the index numbers:
<?php
$primes = array(0=>2, 5=>3, 10=>5, 15=>7, 20=>11);
var_dump($primes);
// array(5) { [0]=> int(2) [5]=> int(3) [10]=> int(5) [15]=> int(7) [20]=> int(11) }
?>
As you can see, the indices still start at 0, but are incremented by five for each successive array element. Now let's do something even more unconventional:
<?php
$primes = array(0=>2, 20=>3, 10=>5, 15=>7, 5=>11);
var_dump($primes);
// array(5) { [0]=> int(2) [20]=> int(3) [10]=> int(5) [15]=> int(7) [5]=> int(11) }
?>
As you can see, we have used the same index numbers for the array as in the previous example, but have changed the order in which they are used. Note, however, that the var-dump() function still lists the array elements in the order in which they were specified, seemingly ignoring the indices. This is somewhat counter intuitive, especially if you are used to working with indexed arrays in languages like C++. It does however highlight the fact that, internally, PHP simply treats all arrays as collections of key-value pairs.
Instead of using the array() function, we can create an array using a shorthand syntax that employs square bracket notation. For example, we could create our indexed prime number array like this:
<?php
$primes = [2, 3, 5, 7, 11];
var_dump($primes);
// array(5) { [0]=> int(2) [1]=> int(3) [2]=> int(5) [3]=> int(7) [4]=> int(11) }
?>
As you can see, we have simply omitted the array() function from the opening line of code and instead placed square brackets around the list of values to be inserted in the array. The output when we apply the var_dump() function to $primes is exactly the same as before.
We can use this shorthand notation in similar fashion to create an associative array. The only difference is that, instead of simply specifying a value for each array element, we will be specifying the array element as a key-value pair. For example:
<?php
$auto = ["Make"=>"Ford", "Model"=>"Escort", "Year"=>"1997"];
var_dump($auto);
// array(3) { ["Make"]=> string(4) "Ford" ["Model"]=> string(6) "Escort" ["Year"]=> string(4) "1997" }
?>
Note that, to make your code easier to read, we can make array declarations span several lines. For example, the array in the example above could be re-written as:
<?php
$auto = [
"Make"=>"Ford",
"Model"=>"Escort",
"Year"=>"1997"
];
?>
As previously stated, each element in an associative array is specified as a key-value pair. Keys and their associated values are separated by the key-value separator (=>), and the array elements appear between the opening and closing square brackets in a comma-separated list.
Note that it is permissible to place a comma after the last element in the array. This is sometimes done in order to make it easier to add new elements at the end of an array, although we prefer not to do this as it looks as though something has been forgotten . . . and where's the hardship in typing a comma before you add an additional element?
Let's suppose we want to create an associative array to hold various details about a person. We might do something like this:
<?php
$person = ["lastName"=>"Bloggs", "firstName"=>"Fred", "age"=>45];
var_dump($person);
// array(3) { ["lastName"]=> string(6) "Bloggs" ["firstName"]=> string(4) "Fred" ["age"]=> int(45) }
?>
As with the array() function, we can specify any number of comma-separated key-value pairs between the opening and closing square brackets. Each key can be either a string or an integer value, although most keys in an associative array tend to be strings that describe the nature of the array element - for example, "name" or "dateOfBirth".
If an integer value is used as a key, it can be written with or without quotes. For example, "3" or simply 3. The key will be stored as an integer either way. Note however that a key specified as "03" would be stored as a string and not as an integer.
Using any datatype other than an integer or a string as a key will result in PHP attempting to convert the key supplied to either an integer or a string. For example, a floating-point number would be truncated to its whole-number part, a variable name would be evaluated and that value converted to either an integer or a string (or, if the variable name was not recognised, to the empty string), and a key consisting of a string value without quotes would generate an error.
Boolean values used as keys will be converted to either 1 (TRUE) or 0 (FALSE), NULL will be converted to the empty string, and attempting to use arrays or objects as keys will generate an error. If the same key is used for two or more different array elements, the last element specified using that key will be stored in the array, as it will have overwritten its predecessors. For example:
<?php
$arr = [FALSE=>"Mrs", TRUE=>"Jane Doe", 0=>"Mr", 1=>"Joe Bloggs"];
var_dump($arr);
// array(2) { [0]=> string(2) "Mr" [1]=> string(10) "Joe Bloggs" }
?>
In this (somewhat confusing!) example, the key FALSE  chosen for the first array element, which had a value of "Mrs" , is converted by PHP to 0, but this array element is then overwritten by the third array element in our array declaration because we specify a key of 0 and a value of "Mr"  for that element. Similarly, the second element specified, which is given a key of TRUE  and a value of "Jane Doe" , has its key converted to 1. That element is subsequently overwritten by the fourth element in our array declaration, because we give that element a key of 1 and a value of "Joe Bloggs" .
If the key for any element in an associative array is omitted altogether, PHP will give it an integer value. If no integer values have yet been used as keys, PHP will use the default value of 0. Otherwise, it will increment the larges integer value previously used as a key by one, and use the resulting integer value. For example:
<?php
$arr = ["Mr", "name"=>"John Smith", 45];
var_dump($arr);
// array(3) { [0]=> string(2) "Mr" ["name"]=> string(10) "John Smith" [1]=> int(45) }
?>
As you can see, it is possible to specify a key for some elements in an associative array and omit the key for other elements, although this could be seen as a somewhat less than methodical approach.
As we have seen, multi dimensional arrays can contain array elements that are themselves arrays, which means they can be used to model complex data structures. Multi-dimensional arrays can have two, three, or an even higher number of dimensions, although keep in mind that each additional dimension will potentially increase the complexity of managing the array.
Like the single-dimensional indexed and associative arrays, multi-dimensional arrays can be created using either the array() function or the shorthand square bracket notation. For the rest of this article, we are going to use the square bracket notation, since it is a little more concise and is generally considered to be more readable.
The following script creates a two-dimensional array containing the names of five students and their test results, and echoes the contents of the array to the screen:
<?php
$students = [
["name"=>"Anderson, N", "score"=>51],
["name"=>"Beckham, D", "score"=>31],
["name"=>"Einstein, A", "score"=>99],
["name"=>"Foster, R", "score"=>95],
["name"=>"Miller, G", "score"=>75]
];
echo "Student Results:<br>";
echo $students[0]["name"] . ": " . $students[0]["score"] . "<br>";
echo $students[1]["name"] . ": " . $students[1]["score"] . "<br>";
echo $students[2]["name"] . ": " . $students[2]["score"] . "<br>";
echo $students[3]["name"] . ": " . $students[3]["score"] . "<br>";
echo $students[4]["name"] . ": " . $students[4]["score"];
// Student Results:
// Anderson, N: 51
// Beckham, D: 31
// Einstein, A: 99
// Foster, R: 95
// Miller, G: 75
?>
The top-level $students array is an indexed array that contains five elements, each of which is an associative array that contains two elements - the name of a student, and that student's test score. Let's take things a stage further and look at an example of a four-dimensional array:
<?php
$orders = [
["orderNum"=>"0123", "cust"=>"Smith & Co", "items"=>
[
["id"=>"1234A", "desc"=>"Widget", "qty"=>6],
["id"=>"5678B", "desc"=>"Sprocket", "qty"=>12],
["id"=>"1066C", "desc"=>"Rocker", "qty"=>3]
]
],
["orderNum"=>"0456", "cust"=>"ACME Inc", "items"=>
[
["id"=>"9876D", "desc"=>"Thingy", "qty"=>5],
["id"=>"5432E", "desc"=>"Gadget", "qty"=>5],
["id"=>"1002F", "desc"=>"Doofer", "qty"=>10]
]
]
];
echo "Orders on hand:<br><br>";
echo "Order no. " . $orders[0]["orderNum"] . " - " . $orders[0]["cust"] . "<br>";
echo "---- Item 1: " . $orders[0]["items"][0]["qty"] . " x ";
echo $orders[0]["items"][0]["id"] . ", " . $orders[0]["items"][0]["desc"] . "<br>";
echo "---- Item 2: " . $orders[0]["items"][1]["qty"] . " x ";
echo $orders[0]["items"][1]["id"] . ", " . $orders[0]["items"][1]["desc"] . "<br>";
echo "---- Item 3: " . $orders[0]["items"][2]["qty"] . " x ";
echo $orders[0]["items"][2]["id"] . ", " . $orders[0]["items"][2]["desc"] . "<br>";
echo "<br>";
echo "Order no. " . $orders[1]["orderNum"] . " - " . $orders[1]["cust"] . "<br>";
echo "---- Item 1: " . $orders[1]["items"][0]["qty"] . " x ";
echo $orders[1]["items"][0]["id"] . ", " . $orders[1]["items"][0]["desc"] . "<br>";
echo "---- Item 2: " . $orders[0]["items"][1]["qty"] . " x ";
echo $orders[1]["items"][1]["id"] . ", " . $orders[1]["items"][1]["desc"] . "<br>";
echo "---- Item 3: " . $orders[0]["items"][2]["qty"] . " x ";
echo $orders[1]["items"][2]["id"] . ", " . $orders[1]["items"][2]["desc"] . "<br>";
// Orders on hand:
//
// Order no. 0123 - Smith & Co
// ---- Item 1: 6 x 1234A, Widget
// ---- Item 2: 12 x 5678B, Sprocket
// ---- Item 3: 3 x 1066C, Rocker
//
// Order no. 0456 - ACME Inc
// ---- Item 1: 5 x 9876D, Thingy
// ---- Item 2: 12 x 5432E, Gadget
// ---- Item 3: 3 x 1002F, Doofer
?>
As you can see, a four-dimensional array is being used here to model customer orders. The top-level $orders array is an indexed array that has two elements, each of which is an associative array that models a single customer order and has the elements orderNum (the order number), cust (the customer's name) and items.
The items element in each order is another indexed array that holds a number of elements, each of which is an associative array that holds the details of one line item on the customer order, including the product ID (id), product description (desc) and quantity ordered (qty).
In this example we have directly accessed each array value in order to output the order details to the screen. In a real application, of course, this would be totally impractical, and we would use a far more sophisticated algorithm, for example using a nested loop construct, in order to greatly simplify things. Nevertheless, this example should give you some idea of the kind of applications in which a multi-dimensional array could be used.
Array elements can be accessed individually using the name of the array variable together with the square bracket notation. In fact, we have already seen some examples of how array elements are accessed in the example scripts we used to demonstrate multi-dimensional arrays. We'll look first at accessing array elements in a one-dimensional array. Consider the following example.
<?php
$primesTo50 = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47];
$count = count($primesTo50);
$largest = $primesTo50[$count-1];
echo "There are $count prime numbers between 0 and 50.<br>";
echo "The largest prime number less than 50 is $largest.";
// There are 15 prime numbers between 0 and 50.
// The largest prime number less than 50 is 47.
?>
Here, we have created an indexed array to hold all of the prime numbers between 0 and 50, in ascending order. We can access each of the array elements and get its value using the element's index number.
In order to find the value of the last item in the array, we have used PHP's built-in count() function to get the number of elements in the array and assign it to $count. We then use the value $count-1 (remembering that indexed arrays are indexed from 0 by default) to access the last item in the array, retrieve its value, and assign that value to $largest.
We could of course make life slightly easier by using PHP's built-in end() function, which works on both indexed and associative arrays, to retrieve the value of the last element in the array. For example:
<?php
$primesTo50 = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47];
$count = count($primesTo50);
$largest = end($primesTo50);
echo "There are $count prime numbers between 0 and 50.<br>";
echo "The largest prime number less than 50 is $largest.";
// There are 15 prime numbers between 0 and 50.
// The largest prime number less than 50 is 47.
?>
In similar fashion, we can access the first element in an array by using PHP's reset() function. Here is an example of using the reset() function with an associative array:
<?php
$auto = [
"Make"=>"Ford",
"Model"=>"Escort",
"Year"=>"1997"
];
echo "The manufacturer of this car is " . reset($auto) . ".";
// The manufacturer of this car is Ford.
?>
For accessing elements other than the first or last element in a one-dimensional associative array, we can again use the name of the array variable with the square bracket notation as we have done with indexed arrays, but instead of using an integer index number we will use a key, which is normally a string (although somewhat perversely, the key can also be an integer). For example:
<?php
$person = [
"firstName"=>"Fred",
"lastName"=>"Bloggs",
"age"=>45,
"occupation"=>"Toolmaker"
];
echo $person["firstName"] . " " . $person["lastName"];
echo " is a " . $person["age"] . "-year-old ";
echo $person["occupation"] . ".";
// Fred Bloggs is a 45-year-old Toolmaker.
?>
Accessing elements in a multidimensional array is also carried out using the array variable's name and the square bracket notation. Unless we are only interested in accessing an element in the top-level array (this is a possibility, since not all top-level array elements in a multi-level array need be arrays), we will have to use a combination of two or more keys, each enclosed within square brackets.
Here is our $students array from an earlier example:
<?php
$students = [
["name"=>"Anderson, N", "score"=>51],
["name"=>"Beckham, D", "score"=>31],
["name"=>"Einstein, A", "score"=>99],
["name"=>"Foster, R", "score"=>95],
["name"=>"Miller, G", "score"=>75]
];
?>
Let's suppose that we want to retrieve the name of the first student in the array and assign it to the variable $firstStudent. We could do this:
$firstStudent = $students[0]["name"];
This would assign the value "Anderson, N" to $firstStudent. We have used an index number (0) to access the first student record in the array because $students is an indexed array. In order to access the student's name, however, we must use the key "name", because each student record is an associative array.
Here is the $orders array - a four-dimensional array - from an earlier example:
$orders = [
["orderNum"=>"0123", "cust"=>"Smith & Co", "items"=>
[
["id"=>"1234A", "desc"=>"Widget", "qty"=>6],
["id"=>"5678B", "desc"=>"Sprocket", "qty"=>12],
["id"=>"1066C", "desc"=>"Rocker", "qty"=>3]
]
],
["orderNum"=>"0456", "cust"=>"ACME Inc", "items"=>
[
["id"=>"9876D", "desc"=>"Thingy", "qty"=>5],
["id"=>"5432E", "desc"=>"Gadget", "qty"=>5],
["id"=>"1002F", "desc"=>"Doofer", "qty"=>10]
]
]
];
Let's suppose we want to retrieve the item description for the second item in the second order and store it in a variable called $order2_2_desc. We could do this:
$order2_2_desc = $orders[1]["items"][1]["desc"];
This would assign the value "Gadget" to $order2_2_desc. We have used a combination of index numbers and keys to retrieve this array element's value because the arrays in this multi-dimensional array are a mix of indexed and associative arrays.
As previously mentioned, we would not normally access elements in a multi-dimensional array in such a piecemeal manner, but we will be exploring better ways to process complex data structures like this elsewhere.
One last thing to note is that attempting to access an array element using a key or index number that does not exist will generate a warning message, and the value returned will be null.
Arrays are dynamic structures that can hold a potentially unlimited amount of data, and they rarely remain static. In a typical application, the number of elements stored in an array will grow or shrink over time as elements are added and removed. We will look here at the ways in which a new element can be added to an existing array.
The simplest way to add an element to an array is through simple assignment using the square brackets notation. In the following example, we create an empty array variable called $trees and add two elements to it:
<?php
$trees = [];
$trees[] = "Oak";
$trees[] = "Ash";
var_dump($trees);
// array(2) { [0]=> string(3) "Oak" [1]=> string(3) "Ash" }
?>
In thus example, we have added each new element without specifying either a numerical index or a key, so the new elements are simply added to the end of the array. This is normally what we want to happen for an indexed array, and it means we don't have to be concerned with finding out what the next index number should be. It may be the case, however, that we want to add an item to an indexed array with a specific index number. For example:
<?php
$trees = ["Oak", "Ash"];
$trees[10] = "Beech";
$trees[] = "Sycamore";
var_dump($trees);
// array(4) { [0]=> string(3) "Oak" [1]=> string(3) "Ash" [10]=> string(5) "Beech" [11]=> string(8) "Sycamore" }
?>
In this example we have created an indexed array called $trees with two elements which will be automatically be allocated the index numbers 0 and 1. We have then added two more elements to the $trees array, but for the first of these ("Beech") we have specified an array index of 10.
The next element added to the $trees array ("Sycamore") is allocated an index number of 11 because we have not specified an index, and because PHP will, by default, allocate an index number one greater than the highest previously allocated index number. But what happens if we add a new element to a previously purely indexed array, but specify a (non-numeric) key? Consider this example:
<?php
$greekAlphabet = ["Alpha", "Beta", "Gamma"];
$greekAlphabet["Δδ"] = "Delta";
print_r($greekAlphabet);
// Array ( [0] => Alpha [1] => Beta [2] => Gamma [Δδ] => Delta )
?>
Before we discuss what is happening here, note that we have switched to using the print_r() function in place of var_dump() to display information about an array variable. We have made the change because the examples we provide from this point onwards will tend to involve a greater number of array elements, and print_r() produces output in a somewhat more human-readable form than var_dump().
What we have demonstrated with this example is that, with PHP, we can add an associative array element, i.e. an array element consisting of a key-value pair, to an indexed array without encountering any problems (although whether we should do so is another matter - it really depends on what we are trying to achieve).
Something else to consider is that, if we add elements to an array without specifying either an index number or a key, PHP will automatically assign an index number. By default, the first index number added to an empty array will be assigned an index of 0, and elements added to the array thereafter will be allocated indices of 1, 2, 3 . . . and so on, in strict numerical order. Suppose, however, we do something like this:
<?php
$trees = [];
$trees[10] = "Beech";
$trees[5] = "Sycamore";
$trees[] = "Ash";
print_r($trees);
// Array ( [10] => Beech [5] => Sycamore [11] => Ash )
?>
Here, we have explicitly given the first two elements added to the $trees array index numbers of 10 and 5 respectively. For the third element allocated to $trees, we have not specified an index number and therefore, as expected this element is automatically allocated an index number of 11. But consider the order in which the array elements are presented - [10]=>Beech, [5]=>Sycamore, [11]=>Ash - so definitely not ordered by index number.
In some other programming languages, the array elements in an indexed array would automatically be sorted by their indices. What this example reaffirms is that PHP really doesn't distinguish between a numeric index and a key. To PHP, they are all just keys, and all array elements are essentially key-value pairs. It also shows quite clearly that array elements are stored in the order in which they are inserted into the array, regardless of key values.
One word of warning here. Whether adding new elements to an array using an index number or a key, keep in mind that using an index number or a key that is already in use in the array will overwrite the element to which that index number or key is currently assigned. Consider the following example:
<?php
$climateZone[3] = "Alpine";
$climateZone[4] = "Desert";
$climateZone[5] = "Subarctic";
$climateZone[6] = "Mediterranean";
//
//
//
$elements = count($climateZone);
$climateZone[$elements] = "Tundra";
print_r($climateZone);
// Array ( [3] => Alpine [4] => Tundra [5] => Subarctic [6] => Mediterranean )
?>
We have allocated consecutive index numbers to the first four array elements in the $climateZone array, starting at 3, perhaps anticipating that we will have a couple of additional climate types to add to the array at a future time that should appear before these elements when the array is sorted and displayed as a list (or whatever).
However, at some point later in our code we want to add another element ("Tundra"), so we use the count() function to get the array length for $climateZone and allocate the result to the new element as its index value. Sure enough, when the contents of the array are displayed "Tundra" is there in the list, but not at the and as expected. And what has happened to "Desert"?
It's pretty easy to see that in this case finding the length of the array does not tell us anything about the array index values already allocated. We are falsely assuming that the array is indexed from zero, presumably having forgotten about our earlier decision to start the indexing at 3. This is an admittedly somewhat contrived example but it does illustrate the point that we should not make assumptions when it comes to allocating array indices. In this case, the following approach would avoid the problem:
<?php
$climateZone[3] = "Alpine";
$climateZone[4] = "Desert";
$climateZone[5] = "Subarctic";
$climateZone[6] = "Mediterranean";
//
//
//
$climateZone[] = "Tundra";
print_r($climateZone);
// Array ( [3] => Alpine [4] => Desert [5] => Subarctic [6] => Mediterranean [7] => Tundra )
?>
As an alternative to using the square brackets notation to add elements to an array, we can use the array_push() function. This function takes two arguments - the name of the array to which we want to add the elements, and a comma-separated list of values. The following example illustrates how we might use the array_push() function:
<?php
$trees = ["Sycamore"];
array_push($trees, "Oak", "Ash", "Beech");
print_r($trees);
// Array ( [0] => Sycamore [1] => Oak [2] => Ash [3] => Beech )
?>
The array_push() function basically treats the array as a stack, and "pushes" one or more elements onto the end of the array, increasing the length of the array by the number of new array elements added to the array. Only use array_push() if you are adding more than one element at a time to the array, otherwise it's better to use the square brackets notation and avoid the overhead of calling a function.
Note that, although the array_push() function can be used to add values to the end of an associative array, it is not designed for this purpose. Any values added to an associative array using array_push() will become indexed values with automatically allocated indices.
The array_push() function cannot be used to add key-value pairs to an associative array, and is intended to be used primarily for adding elements to the end of an indexed array. Adding key-value pairs to an array should be handled using the $array['key'] = $value syntax. For example:
<?php
$greekAlphabet = ["Αα"=>"Alpha", "Ββ"=>"Beta", "Γγ"=>"Gamma"];
$greekAlphabet["Δδ"] = "Delta";
print_r($greekAlphabet);
// Array ( [Αα] => Alpha [Ββ] => Beta [Γγ] => Gamma [Δδ] => Delta )
?>
Adding multiple items to an associative array can be handled using the += assignment operator, as the following example demonstrates:
<?php
$greekAlphabet = ["Αα"=>"Alpha", "Ββ"=>"Beta", "Γγ"=>"Gamma"];
$greekAlphabet += ["Δδ"=>"Delta", "Εε"=>"Epsilon","Ζζ"=>"Zeta"];
print_r($greekAlphabet);
// Array ( [Αα] => Alpha [Ββ] => Beta [Γγ] => Gamma [Δδ] => Delta [Εε] => Epsilon [Ζζ] => Zeta )
?>
Adding an element to the beginning of an array can be achieved using the array_unshift() function. This function takes two arguments - the name of an array variable, and a comma-separated list of one or more values to be added at the start of the array. For example:
<?php
$trees = ["Oak", "Ash", "Beech"];
print_r($trees);
echo "<br>";
array_unshift($trees, "Birch", "Sycamore", "Elm");
print_r($trees);
// Array ( [0] => Oak [1] => Ash [2] => Beech )
// Array ( [0] => Birch [1] => Sycamore [2] => Elm [3] => Oak [4] => Ash [5] => Beech )
?>
Note that the indices of each of the elements stored in the array before the new elements are inserted in the array are incremented by a value equal to the number of new elements added. As with the array_push() function, array_shift() can be used to add values to the beginning of an associative array, but it is not designed for that purpose.
Any values added to the front of an associative array using array_shift() will become indexed values with automatically allocated indices. The array_shift() function cannot be used to add key-value pairs to the start of an associative array, and is intended to be used primarily for adding elements to the start of an indexed array.
There are several ways to remove an element from an array. If you know the index number or key of the array element to be removed, you can use PHP's unset() function. The unset() function can be used to remove just about any kind of variable, including an entire array. It takes as its argument a comma-separated list of variables, or in the current context, array elements. In the following example, we use unset() to remove the second and third elements of an array:
<?php
$trees = ["Oak", "Ash", "Beech", "Elm"];
print_r($trees);
echo "<br>";
unset($trees[1], $trees[2]);
print_r($trees);
echo "<br>";
// Array ( [0] => Oak [1] => Ash [2] => Beech [3] => Elm )
// Array ( [0] => Oak [3] => Elm )
?>
Note that unset() does not reindex the array after it has removed an element. If you remove elements from the middle of an array, they will simply no longer exist. The remaining elements will have the same indices they had before the removal. If we want the array to be re-indexed, we will need to use the array_values() function.
The array_values() function takes the name of an array variable as its argument, returns all of the values in the array, and indexes the array numerically. The return value can be assigned either to the original array or to a new array variable. We could, for example, do this:
<?php
$trees = ["Oak", "Ash", "Beech", "Elm"];
print_r($trees);
echo "<br>";
unset($trees[1], $trees[2]);
print_r($trees);
echo "<br>";
$trees = array_values($trees);
print_r($trees);
// Array ( [0] => Oak [1] => Ash [2] => Beech [3] => Elm )
// Array ( [0] => Oak [3] => Elm )
// Array ( [0] => Oak [1] => Elm )
?>
Note that it is perfectly possible to use the array_values() function on an associative array, but you should be aware that the resulting array will be an indexed array. The keys in the original array are replaced by integer values in the new array.
We can use the unset() function to delete array elements in an associative array in much the same was as for an indexed array. The only difference is that we specify a key instead of an index. For example:
<?php
$countries = [
"DE"=>"Germany",
"FR"=>"France",
"DK"=>"Denmark",
"BE"=>"Belgium",
"NL"=>"Netherlands"
];
print_r($countries);
echo "<br>";
unset($countries["DK"]);
print_r($countries);
echo "<br>";
// Array ( [DE] => Germany [FR] => France [DK] => Denmark [BE] => Belgium [NL] => Netherlands )
// Array ( [DE] => Germany [FR] => France [BE] => Belgium [NL] => Netherlands )
?>
We can also use the array_splice() function to remove elements from an array. The array_splice() function is actually designed for removing part of an array and replacing it with another array, and we'll be exploring this usage in due course. For now, however, we'll be using it purely in order to remove one or more elements from an array. The function's return value is a new array containing the elements removed from the original array, although we're not really interested in that here.
The array_splice() function takes four arguments, only the first two of which are mandatory. The first argument is the name of the target array variable. The second is an offset from the start of the array, i.e. the point in the array where we want to start deleting elements. The third argument is length, i.e. the number of elements to delete. The last argument is the array to be used to replace the array elements removed, but we won't be using that here.
Note that, if the integer value supplied for the offset is negative, the offset is taken from the end of the array, so an offset of -2 (for example) would remove the last two items in the array. Similarly, if length is negative, then the end of the removed portion will be that number of elements from the end of the array. In the following example, we will use array_splice() to remove the third and fourth elements from an array:
<?php
$countries = [
"DE"=>"Germany",
"FR"=>"France",
"DK"=>"Denmark",
"BE"=>"Belgium",
"NL"=>"Netherlands"
];
print_r($countries);
echo "<br>";
array_splice($countries, 2, 2);
print_r($countries);
// Array ( [DE] => Germany [FR] => France [DK] => Denmark [BE] => Belgium [NL] => Netherlands )
// Array ( [DE] => Germany [FR] => France [NL] => Netherlands )
?>
If no value is given for length, array_splice() removes all array elements from the element specified by offset to the end of the array. If the value given for length is 0, no elements are removed.
When array_splice() is applied to an associative array, the key values of elements remaining in the array are preserved. However, unlike the unset() function, array_splice() will re-index the elements in an indexed array. Here is an example:
<?php
$trees = [
"Oak",
"Ash",
"Beech",
"Birch",
"Elm",
"Cedar"
];
print_r($trees);
echo "<br>";
array_splice($trees, 2, 2);
print_r($trees);
// Array ( [0] => Oak [1] => Ash [2] => Beech [3] => Birch [4] => Elm [5] => Cedar )
// Array ( [0] => Oak [1] => Ash [2] => Elm [3] => Cedar )
?>
It is worth noting that array_splice() can be used to remove all of the elements in an array, leaving the array empty, simply by setting offset to 0 and not specifying length. For example:
<?php
$trees = [
"Oak",
"Ash",
"Elm",
"Cedar"
];
print_r($trees);
echo "<br>";
array_splice($trees, 0);
print_r($trees);
// Array ( [0] => Oak [1] => Ash [2] => Elm [3] => Cedar )
// Array ( )
?>
Similarly, unset() can be used to remove an array entirely by passing it the name of the array variable on its own rather than a list of array elements. For example:
<?php
$primesTo10 = [2,3,5,7];
print_r($primesTo10);
echo "<br>";
unset($primesTo10);
print_r($primesTo10);
// Array ( [0] => 2 [1] => 3 [2] => 5 [3] => 7 )
//
// Warning: Undefined variable $primesTo10 . . .
?>
We saw earlier that the array_push() function can be used to add an element to the end of an array. PHP has a complimentary function, array_pop(), which can be used to remove an element from the end of the array. It takes the name of the target array variable as its argument, and returns the value of the array element removed. Here is an example:
<?php
$countries = [
"DE"=>"Germany",
"FR"=>"France",
"DK"=>"Denmark",
"BE"=>"Belgium",
"NL"=>"Netherlands"
];
print_r($countries);
echo "<br>";
$value = array_pop($countries);
print_r($countries);
echo "<br>";
print_r($value);
// Array ( [DE] => Germany [FR] => France [DK] => Denmark [BE] => Belgium [NL] => Netherlands )
// Array ( [DE] => Germany [FR] => France [DK] => Denmark [BE] => Belgium )
// Netherlands
?>
The array_unshift() function, which adds an element to the start of an array, also has its counterpart in the array_shift() function, which removes the first element in the array and returns the value of the array element removed. Here is an example:
<?php
$countries = [
"DE"=>"Germany",
"FR"=>"France",
"DK"=>"Denmark",
"BE"=>"Belgium",
"NL"=>"Netherlands"
];
print_r($countries);
echo "<br>";
$value = array_shift($countries);
print_r($countries);
echo "<br>";
print_r($value);
// Array ( [DE] => Germany [FR] => France [DK] => Denmark [BE] => Belgium [NL] => Netherlands )
// Array ( [FR] => France [DK] => Denmark [BE] => Belgium [NL] => Netherlands )
// Germany
?>
It is very often the case that we need to change one or more values in an array in order to reflect changing circumstances. For example, a customer record may need to be updated due to a change in address, and sports league tables need to be regularly updated to reflect points accrued by the participating teams or individuals.
In order to update an array element, we simply need to access that array element using one of the methods described earlier, and assigning a new value to it. Let's look at an example of updating values in an indexed array:
<?php
$lotteryNums = [4, 15, 25, 31,36, 39];
//
//
//
echo "Last week's lottery numbers:<br>";
echo "$lotteryNums[0], $lotteryNums[1], $lotteryNums[2], ";
echo "$lotteryNums[3], $lotteryNums[4], $lotteryNums[5] <br><br>";
$lotteryNums[0] = 7;
$lotteryNums[1] = 13;
$lotteryNums[2] = 27;
$lotteryNums[3] = 40;
$lotteryNums[4] = 47;
$lotteryNums[5] = 49;
echo "This week's lottery numbers:<br>";
echo "$lotteryNums[0], $lotteryNums[1], $lotteryNums[2], ";
echo "$lotteryNums[3], $lotteryNums[4], $lotteryNums[5]";
// Last week's lottery numbers:
// 4, 15, 25, 31, 36, 39
//
// This week's lottery numbers:
// 7, 13, 27, 40, 47, 49
?>
Updating array elements in associative arrays works pretty much the same, except that we use key values inside the square brackets instead of index numbers. For example:
<?php
$averageRainEN = [
"Jan"=>0,
"Feb"=>0,
"Mar"=>0,
];
$averageRainEN["Jan"] = 99;
$averageRainEN["Feb"] = 81;
$averageRainEN["Mar"] = 52;
echo "Average monthly rainfall for England (mm):<br><br>";
echo "Jan: " . $averageRainEN["Jan"] . " mm<br>";
echo "Feb: " . $averageRainEN["Feb"] . " mm<br>";
echo "Mar: " . $averageRainEN["Mar"] . " mm<br>";
// Average monthly rainfall for England (mm):
//
// Jan: 99 mm
// Feb: 81 mm
// Mar: 52 mm
?>
Updating multi-dimensional arrays is also fairly straightforward, except that now we are working with more than one array index or key in order to assign a new value to an array variable. In the following example, we have created a two-dimensional array called $students to hold the names of a number of students and their test scores. When the array is created, all of the student scores are given an initial value of 0. Later in our script we update each student's score to reflect the score they achieved on the test.
<?php
$students = [
["name"=>"Anderson, N", "score"=>0],
["name"=>"Beckham, D", "score"=>0],
["name"=>"Foster, R", "score"=>0],
["name"=>"Miller, G", "score"=>0]
];
//
//
//
$students[0]["score"] = 51;
$students[1]["score"] = 31;
$students[2]["score"] = 95;
$students[3]["score"] = 75;
echo "Student Results:<br>";
echo $students[0]["name"] .": " . $students[0]["score"] . "<br>";
echo $students[1]["name"] .": " . $students[1]["score"] . "<br>";
echo $students[2]["name"] .": " . $students[2]["score"] . "<br>";
echo $students[3]["name"] .": " . $students[3]["score"];
// Student Results:
// Anderson, N: 51
// Beckham, D: 31
// Foster, R: 95
// Miller, G: 75
?>
Here, we use a combination of indices and keys to access and update the student scores, because the $students array is an indexed array, but each of its elements is an associative array.
Array destructuring is a process by which we extract some or all of the values stored in an array and assign those values to individual variables that are easier to work with. The most widely used (and probably the most straightforward) method of destructuring an array involves the use of square brackets. Consider the following example:
<?php
$greekAlphabet = ["Αα", "Ββ", "Γγ", "Δδ", "Εε", "Ζζ"];
[$alpha, $beta, $gamma, $delta, $epsilon, $zeta] = $greekAlphabet;
echo "$alpha, $beta, $gamma, $delta, $epsilon, $zeta";
// Αα, Ββ, Γγ, Δδ, Εε, Ζζ
?>
As you can see, we list the names of the variables we wish to create as a comma-delimited list within square brackets, creating an array-like language structure . We then assign an array variable to this structure using the assignment operator. The value of each array element in the array will be assigned to one of the variables listed, in the order in which the variables appear in the list.
In this example, the value of $greekAlphabet[0] is assigned to the first variable listed ($alpha), the value of $greekAlphabet[1] is assigned to the second variable listed ($beta), and so on. If there are more variables listed than there are elements in the array, a warning will be generated. For example:
<?php
$greekAlphabet = ["Αα", "Ββ", "Γγ", "Δδ", "Εε", "Ζζ"];
[$alpha, $beta, $gamma, $delta, $epsilon, $zeta, $eta] = $greekAlphabet;
echo "$alpha, $beta, $gamma, $delta, $epsilon, $zeta, $eta";
// Warning: Undefined array key 6 . . .
// Αα, Ββ, Γγ, Δδ, Εε, Ζζ
?>
If there are fewer variables listed than there are elements in the array, any array elements that are not assigned to a variable are simply ignored. For example:
<?php
$greekAlphabet = ["Αα", "Ββ", "Γγ", "Δδ", "Εε", "Ζζ"];
[$alpha, $beta, $gamma, $delta, $epsilon] = $greekAlphabet;
// Αα, Ββ, Γγ, Δδ, Εε
?>
Associative arrays can also be destructured in this manner, although whereas the index numbers used an indexed array are implicit in the ordering of the variable names within the square bracketed list, we must explicitly state the key for each element in an associative array whose value we wish to retrieve and assign to a variable. Array keys and their corresponding variable names are separated within the bracketed list using the key-value separator (=>). For example:
<?php
$averageRainfall = [
"Jan"=>99,
"Feb"=>81,
"Mar"=>52,
];
["Jan"=>$AveJan, "Feb"=>$AveFeb, "Mar"=>$AveMar] = $averageRainfall;
echo "Average rainfall for first quarter (mm):<br><br>";
echo "Jan: $AveJan mm<br>";
echo "Feb: $AveFeb mm<br>";
echo "Mar: $AveMar mm";
// Average rainfall for first quarter (mm):
//
// Jan: 99 mm
// Feb: 81 mm
// Mar: 52 mm
?>
For indexed arrays, we can omit variables for specific key elements by leaving their positions within the comma separated list blank (note that this does not work for associative arrays). For example, suppose we just want to extract the symbol for the third letter of the Greek alphabet (Gamma) from $greekAlphabet and assign it to the variable $gamma. We could do this:
<?php
$greekAlphabet = ["Αα", "Ββ", "Γγ", "Δδ", "Εε", "Ζζ"];
[, , $gamma] = $greekAlphabet;
echo $gamma;
// Γγ
?>
For associative arrays, in order to selectively assign array element values to one or more variables, instead leaving blank spaces before comma separators, we list only the keys of the array elements we are interested in, together with the names of their target variables. For example
<?php
$averageRainfall = [
"Jan"=>99,
"Feb"=>81,
"Mar"=>52,
];
["Feb"=>$AveFeb] = $averageRainfall;
echo "Average rainfall for February: $AveFeb mm";
// Average rainfall for February (mm): 81 mm
?>
The list() function (actually more of a language construct than a function) provided by PHP can also be used to destructure arrays. For example:
<?php
$greekAlphabet = ["Αα", "Ββ", "Γγ", "Δδ", "Εε", "Ζζ"];
list($alpha, $beta, $gamma, $delta, $epsilon, $zeta) = $greekAlphabet;
echo "$alpha, $beta, $gamma, $delta, $epsilon, $zeta";
// Αα, Ββ, Γγ, Δδ, Εε, Ζζ
?>
As with the square-bracketed list notation, if there are more variables listed than there are elements in the array, a warning will be generated. If there are fewer variables listed than there are elements in the array, array elements that are not assigned to a variable are ignored. We can also destructure multi-dimensional arrays, but will be exploring that topic in a later article.
PHP provides various ways in which we can create arrays from variables of other datatypes. The result will depend on the kind of variable. Converting a variable with a scalar datatype to an array (i.e. an integer, floating-point, Boolean or string variable) will result in an array that contains a single element with an index of 0. For example:
<?php
$num = 10;
$arr = (array) $num;
var_dump($arr);
// array(1) { [0]=> int(10) }
?>
In the above example we have cast the value of $num - an integer variable - to an array in order to create the array variable $arr. We could have achieved exactly the same end result by doing this:
$arr = array($num);
or this:
$arr = [$num];
Of more interest is the ability to create an array from an object, especially if you have pre-existing code that works with associative arrays. When we convert an object to an array, the result is an associative array whose elements are the object's properties. Each key-value pair in the newly-created associative array consists of a member variable name (which becomes the key for the array element) and its associated value. Consider the following example:
<?php
class car {
public $make;
public $model;
public $color;
public function __construct($make, $model, $color) {
$this->make = $make;
$this->model = $model;
$this->color = $color;
}
public function report() {
return "This car is a " . $this->color . " " . $this->make . " " . $this->model . ".";
}
}
$myCar = new car("Fiat", "Punto", "White");
$arrMyCar = (array) $myCar;
print_r($arrMyCar);
// Array ( [make] => Fiat [model] => Punto [color] => White )
?>
We can also use PHP's get_object_vars() function. The following code produces exactly the same result as the previous example:
<?php
class car {
public $make;
public $model;
public $color;
public function __construct($make, $model, $color) {
$this->make = $make;
$this->model = $model;
$this->color = $color;
}
public function report() {
return "This car is a " . $this->color . " " . $this->make . " " . $this->model . ".";
}
}
$myCar = new car("Fiat", "Punto", "White");
$arrMyCar = get_object_vars($myCar);
print_r($arrMyCar);
// Array ( [make] => Fiat [model] => Punto [color] => White )
?>
There may be times when we want to convert the contents of an array to a string that contains all of the elements of the array, separated by an appropriate string separator such as a comma followed by a space. There are various reasons why we might want to do this. We might, for example, want a more human-readable representation of the array's contents, or we might require a string representation of the array for the purposes of debugging.
PHP provides the implode() function for the purpose of converting arrays to strings. The implode() function takes two arguments - an optional string separator and the name of an array variable. The return value is a string containing all of the elements in the array, separated by with the string separator (if specified).
The array elements can be strings, numeric values or Boolean values (or a mixture of these datatypes). Non-string array elements will be automatically converted to their string representation. In the following example, an array of strings is converted to a single string variable:
<?php
$trees = ["Oak", "Ash", "Beech", "Elm", "Birch"];
$strTrees = implode(", ", $trees);
var_dump($strTrees);
// string(27) "Oak, Ash, Beech, Elm, Birch"
?>
And in this example, of an array of integer values is converted to a string variable:
<?php
$primesTo50 = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47];
$strPrimesTo50 = implode(",", $primesTo50);
var_dump($strPrimesTo50);
// string(40) "2,3,5,7,11,13,17,19,23,29,31,37,41,43,47"
?>
One example of where the implode() function can be useful is in the creation of comma-separated value (CSV) files, which are plain text files containing a list of comma-separated values. These files are typically used to store tabular data, and to transfer data between spreadsheet and database applications.
Sometimes we may wish to break a large array up into smaller arrays, maybe in order to speed up processing time, make the data easier to manage, or to present the data to an end user in bite-sized "chunks". We can achieve this using PHP's array_chunk() function.
The array_chunk() function takes three arguments - the name of the array variable to be split, a length argument that specifies the maximum number of array elements allowed per chunk, and a preserve_keys argument - a Boolean value that specifies whether the original array keys will be preserved. This argument is set to FALSE by default, which means that each chunk will automatically be reindexed numerically.
The return value is a multi-dimensional array in which each sub-array holds up to length elements. Let's look at an example:
<?php
$primesTo50 = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47];
$arrChunked = array_chunk($primesTo50, 5);
print_r($arrChunked[0]);
echo "<br>";
print_r($arrChunked[1]);
echo "<br>";
print_r($arrChunked[2]);
echo "<br>";
// Array ( [0] => 2 [1] => 3 [2] => 5 [3] => 7 [4] => 11 )
// Array ( [0] => 13 [1] => 17 [2] => 19 [3] => 23 [4] => 29 )
// Array ( [0] => 31 [1] => 37 [2] => 41 [3] => 43 [4] => 47 )
?>
Since we know that the $primesTo50 array holds fifteen items and we have set the length argument to 5, the $arrChunked array will hold three elements, each of which is a zero-indexed sub-array that holds five integer values. This is what happens if we set the preserve_keys argument to TRUE:
<?php
$primesTo50 = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47];
$arrChunked = array_chunk($primesTo50, 5, TRUE);
print_r($arrChunked[0]);
echo "<br>";
print_r($arrChunked[1]);
echo "<br>";
print_r($arrChunked[2]);
echo "<br>";
// Array ( [0] => 2 [1] => 3 [2] => 5 [3] => 7 [4] => 11 )
// Array ( [5] => 13 [6] => 17 [7] => 19 [8] => 23 [9] => 29 )
// Array ( [10] => 31 [11] => 37 [12] => 41 [13] => 43 [14] => 47 )
?>
As you can see, this time, although the same values are stored in each sub-array as before, the index numbers associated with each array element are the same as they were for these elements in the original array. This issue can be critical for associative arrays. Consider the following example:
<?php
$greekAlphabet = ["Αα"=>"Alpha", "Ββ"=>"Beta", "Γγ"=>"Gamma","Δδ"=>"Delta"];
$alphaChunked = array_chunk($greekAlphabet, 2);
print_r($alphaChunked[0]);
echo "<br>";
print_r($alphaChunked[1]);
// Array ( [0] => Alpha [1] => Beta )
// Array ( [0] => Gamma [1] => Delta )
?>
In this kind of situation, we would almost certainly want to preserve the keys from the original array, since they contain meaningful information (i.e. the upper and lower-case characters from the Greek alphabet that match the character names stored in the array). That being the case, we should ensure that the preserve_keys argument is set to TRUE:
<?php
$greekAlphabet = ["Αα"=>"Alpha", "Ββ"=>"Beta", "Γγ"=>"Gamma","Δδ"=>"Delta"];
$alphaChunked = array_chunk($greekAlphabet, 2, TRUE);
print_r($alphaChunked[0]);
echo "<br>";
print_r($alphaChunked[1]);
// Array ( [Αα] => Alpha [Ββ] => Beta )
// Array ( [Γγ] => Gamma [Δδ] => Delta )
?>
Sometimes we might want to merge the contents of two or more arrays into a single array. PHP provides several ways in which we can merge arrays, and the method used will depend upon what exactly we are trying to achieve. We'll look first at the array_merge() function. This function takes a comma-separated list of array variables as its argument, and returns a new array that is the result of combining those arrays. Here is an example:
<?php
$trees1 = ["Oak", "Ash"];
$trees2 = ["Beech", "Elm", "Sycamore", "Cedar"];
$trees3 = ["Larch", "Elm", "Maple"];
$myTrees = array_merge($trees1, $trees2, $trees3);
print_r($trees1);
echo "<br>";
print_r($trees2);
echo "<br>";
print_r($trees3);
echo "<br>";
print_r($myTrees);
// Array ( [0] => Oak [1] => Ash )
// Array ( [0] => Beech [1] => Elm [2] => Sycamore [3] => Cedar )
// Array ( [0] => Larch [1] => Elm [2] => Maple )
// Array ( [0] => Oak [1] => Ash [2] => Beech [3] => Elm [4] => Sycamore [5] => Cedar [6] => Larch [7] => Elm [8] => Maple )
?>
As you can see from the example, all of the elements from the three (indexed) arrays passed to the array_merge() function as input ($trees1, $trees2 and $trees3) have been merged to form the $myTrees array. Note that the indices from the input arrays are not preserved - the new merged array is indexed incrementally, starting from 0. Note also that duplicate values are not removed by the merge process, so $myTrees contains two elements with the value "Elm".
Now let's look at an example of merging two associative arrays. In the script below, we create three separate associative arrays, each of which stores the names of some of the letters of the Greek alphabet, with their corresponding lower-case symbol as the key in each case. Here is the code:
<?php
$alphaGRlower1 = ["α"=>"Alpha", "β"=>"Beta", "γ"=>"Gamma"];
$alphaGRlower2 = ["δ"=>"Delta", "ε"=>"Epsilon","ζ"=>"Zeta"];
$alphaGRlower3 = ["ζ"=>"Zeta", "η"=>"Eta", "θ"=>"Theta","ι"=>"Iota"];
$myAlphaGRlower = array_merge($alphaGRlower1, $alphaGRlower2, $alphaGRlower3);
print_r($myAlphaGRlower);
// Array ( [α] => Alpha [β] => Beta [γ] => Gamma [δ] => Delta [ε] => Epsilon [ζ] => Zeta [η] => Eta [θ] => Theta [ι] => Iota )
?>
In this example we have merged three arrays containing a total of ten elements between them. Note however that the element consisting of key-value pair "ζ"=>"Zeta" appears in two of the input arrays ($alphaGRlower2 and $alphaGRlower3), but only appears once in the merged array. If two or more input arrays have the same (non-numeric) keys, the merged array created by array_merge() will store only the last element it encounters with that key. Previously encountered elements with the same key are overwritten.
We can also merge two arrays using the array union operator (+), which takes two arrays and merges them, creating a new array with keys from both arrays. If both arrays contain an element with the same key, the element from the first array overwrites its counterpart in the second array. Here is an example:
<?php
$alphaGR1 = ["Αα"=>"Alpha", "Ββ"=>"Beta", "Γγ"=>"Gamma", "Δδ"=>"Delta1"];
$alphaGR2 = ["Δδ"=>"Delta2", "Εε"=>"Epsilon","Ζζ"=>"Zeta"];
$myAlphaGR = $alphaGR1 + $alphaGR2;
print_r($myAlphaGR);
// Array ( [Αα] => Alpha [Ββ] => Beta [Γγ] => Gamma [Δδ] => Delta1 [Εε] => Epsilon [Ζζ] => Zeta )
?>
If there are duplicate keys within the same array, the last element with that key overwrites any previous elements with the same key within that array. For example:
<?php
$alphaGR1 = ["Αα"=>"Alpha", "Ββ"=>"Beta", "Γγ"=>"Gamma"];
$alphaGR2 = ["Δδ"=>"Delta1", "Εε"=>"Epsilon","Ζζ"=>"Zeta", "Δδ"=>"Delta2"];
$myAlphaGR = $alphaGR1 + $alphaGR2;
print_r($myAlphaGR);
// Array ( [Αα] => Alpha [Ββ] => Beta [Γγ] => Gamma [Δδ] => Delta2 [Εε] => Epsilon [Ζζ] => Zeta )
?>
We can also use the union operator to combine multiple arrays (in this case, the same rules apply to duplicate keys - within arrays the last element wins, but between arrays the first element wins). Here is an example of using the union operator to combine three arrays:
<?php
$alphaGR1 = ["Αα"=>"Alpha", "Ββ"=>"Beta", "Γγ"=>"Gamma"];
$alphaGR2 = ["Δδ"=>"Delta2", "Εε"=>"Epsilon","Ζζ"=>"Zeta"];
$alphaGR3 = ["Ηη"=>"Eta", "Θθ"=>"Theta","Ιι"=>"Iota"];
$myAlphaGR = $alphaGR1 + $alphaGR2 + $alphaGR3;
print_r($myAlphaGR);
// Array ( [Αα] => Alpha [Ββ] => Beta [Γγ] => Gamma [Δδ] => Delta2 [Εε] => Epsilon [Ζζ] => Zeta [Ηη] => Eta [Θθ] => Theta [Ιι] => Iota )
?>
What is also sometimes useful is the ability to combine two arrays in order to create a new associative array, using the stored values from one of the arrays as the keys for the new array, and the stored values from the other array as its values. We can achieve this using the PHP array_combine() function, which takes the name of two array variables as its arguments, and returns the new combined array. For example:
<?php
$alphaGRKeys = ["Αα", "Ββ", "Γγ", "Δδ", "Εε","Ζζ"];
$alphaGRVals = ["Alpha", "Beta", "Gamma", "Delta2", "Epsilon", "Zeta"];
$myAlphaGR = array_combine($alphaGRKeys, $alphaGRVals);
print_r($myAlphaGR);
// Array ( [Αα] => Alpha [Ββ] => Beta [Γγ] => Gamma [Δδ] => Delta2 [Εε] => Epsilon [Ζζ] => Zeta )
?>
The values from the first array passed to array_combine() become the keys of the new array, and the values from the second array become the stored values. Note that either or both of the arrays passed to array_combine() as arguments can be associative arrays. Only the stored values are used to create the key-value pairs for the elements of the combined array. Note also that the input arrays must have the same number of elements, or a fatal error will be thrown.
The last method we will introduce here for merging arrays involves the use of the spread operator (...), sometimes called the splat operator, which behaves in a similar way to the array_merge() function. To demonstrate, we'll re-write one of our earlier examples using the spread operator:
<?php
$trees1 = ["Oak", "Ash"];
$trees2 = ["Beech", "Elm", "Sycamore", "Cedar"];
$trees3 = ["Larch", "Elm", "Maple"];
$myTrees = [...$trees1, ...$trees2, ...$trees3];
print_r($trees1);
echo "<br>";
print_r($trees2);
echo "<br>";
print_r($trees3);
echo "<br>";
print_r($myTrees);
// Array ( [0] => Oak [1] => Ash )
// Array ( [0] => Beech [1] => Elm [2] => Sycamore [3] => Cedar )
// Array ( [0] => Larch [1] => Elm [2] => Maple )
// Array ( [0] => Oak [1] => Ash [2] => Beech [3] => Elm [4] => Sycamore [5] => Cedar [6] => Larch [7] => Elm [8] => Maple )
?>
As you can see, using the spread operator we get exactly the same result as we got using the array_merge() function. In fact, the spread operator should be faster than array_merge() because it does not require the overhead of a function call. The spread operator also works with associative arrays. For example:
<?php
$alphaGRlower1 = ["α"=>"Alpha", "β"=>"Beta", "γ"=>"Gamma"];
$alphaGRlower2 = ["δ"=>"Delta", "ε"=>"Epsilon","ζ"=>"Zeta"];
$alphaGRlower3 = ["ζ"=>"Zeta", "η"=>"Eta", "θ"=>"Theta","ι"=>"Iota"];
$myAlphaGRlower = [...$alphaGRlower1, ...$alphaGRlower2, ...$alphaGRlower3];
print_r($myAlphaGRlower);
// Array ( [α] => Alpha [β] => Beta [γ] => Gamma [δ] => Delta [ε] => Epsilon [ζ] => Zeta [η] => Eta [θ] => Theta [ι] => Iota )
?>
Before proceeding, we should perhaps also mention the array_merge_recursive() function, which (as the name suggests) merges two or more arrays recursively. This values of each array passed to the array_merge_recursive() function as an argument are appended to the end of the previous one. The recursive part comes into play when one or more of the elements in one of the input arrays is itself an array. We'll investigate this function in more detail in another article. For now, we'll file it away for future reference.
Because arrays are dynamic data structures, often subject to constant change, and because a single array can hold a very large number of elements - only really limited by the amount of memory available to the system on which a script or program is running - it is often impractical to address array elements individually. This will be the case, for example, when we wish to display the entire contents of an array on screen in a particular format.
In situations where we need to carry out the same operation on every element in an array, the only realistic option is to traverse (or iterate over) the array using a loop construct that allows us to process each element in turn without having to worry about explicitly providing an index or a key for each element. We'll be talking about loop constructs in a more general sense in the next article, but for now we will consider them only in the context of working with arrays.
For indexed arrays, the simplest option is the for loop. We'll start with a simple example. Suppose we just want to output the values stored in an array as a numbered list. We could do something like this:
<?php
$trees = ["Oak", "Ash", "Beech", "Elm", "Sycamore", "Cedar", "Larch", "Maple"];
$count = count($trees);
echo "Trees:<br>";
for($i = 0; $i < $count; $i++) {
$index = $i+1;
echo "<br>$index. $trees[$i]";
}
// Trees:
//
// 1. Oak
// 2. Ash
// 3. Beech
// 4. Elm
// 5. Sycamore
// 6. Cedar
// 7. Larch
// 8. Maple
?>
In this example, we use the count() function to get the length of the $trees array, assign the result to $count, and set up our for loop to process $count number of array elements. Because we want the first item in our list to be prefixed with "1. ", and not "0. ", we create the $index variable, and set its value to i + 1 on each iteration of the loop. Note that in order for the for loop to work correctly, the array must be indexed from zero, and that there must be no gaps in the array. If necessary, re-index the array using one of PHP's built-in functions, like array_values() or even range(), which lets you specify a specific range of inex numbers to use.
The for loop is sometimes called a counting loop because it repeats some maximum number of times, depending on the maximum value of its internal counter variable (declared as $i in the above example). We can also use a foreach loop to iterate over an indexed array. The syntax of the foreach loop when used with an indexed array is:
foreach($array as $value) {
// code to be executed for each array element
}
Here, $array is the name of the array variable we are traversing, and $value is the name of the temporary variable used to store the value of each array element as we loop through the array.
The foreach loop does not require a counter variable, so we don't need to use the count() function to get the length of the array. On the other hand, it does not keep track of the number of array items either. That means that if we want to produce a numbered list of array elements like we did in the previous example, we have to use an separate counter variable to represent the list index. For example:
<?php
$trees = ["Oak", "Ash", "Beech", "Elm", "Sycamore", "Cedar", "Larch", "Maple"];
$index = 0;
echo "Trees:<br>";
foreach($trees as $tree) {
$index += 1;
echo "<br>$index. $tree";
}
// Trees:
//
// 1. Oak
// 2. Ash
// 3. Beech
// 4. Elm
// 5. Sycamore
// 6. Cedar
// 7. Larch
// 8. Maple
?>
Note that instead of declaring the external variable $index, we could have done something like this:
foreach($trees as $index=>$tree) {
$index += 1;
echo "<br>$index. $tree";
}
This works well, providing there are no gaps in our indexed array, that any elements that have been assigned index numbers occupy the correct position within the array, and that no index numbers have been duplicated. Otherwise, the list we produce will not be sequentially numbered and may be missing some elements. The following example illustrates the point:
<?php
$trees = ["Oak", 3=>"Ash", "Beech", "Elm", "Sycamore", 3=>"Cedar", "Larch", "Maple"];
echo "Trees:<br>";
foreach($trees as $index=>$tree) {
$index += 1;
echo "<br>$index. $tree";
}
// Trees:
//
// 1. Oak
// 4. Cedar
// 5. Beech
// 6. Elm
// 7. Sycamore
// 8. Larch
// 9. Maple
?>
In this example, not only does our list have a gap - it jumps from item 1 straight to item 4 - but there is a value missing from the list ("Ash"). Of course, it could be that this is the behaviour we require, but it highlights once more the fact that PHP sees all arrays as associative arrays in the sense that array indices are also treated as keys, and this is something we should always be aware of when working with arrays in PHP.
The foreach loop comes into its own when we want to process associative arrays, because not only do we not need to know how many items are in an array beforehand, we can also easily retrieve and output the keys for each element in the array as well as the values - something that cannot be accomplished in a straightforward manner using a for loop. The syntax of the foreach loop when used with an associative array is:
foreach($array as $key=>$value) {
// code to be executed for each array element
}
Here, $array is the name of the array variable we are traversing, and $key and $value are the names of the temporary variables we use to store the key and value respectively for each array element as we loop through the array (note that $key=> is optional). Let's look at an example:
<?php
$alphaGR = [
"Αα"=>"Alpha",
"Ββ"=>"Beta",
"Γγ"=>"Gamma",
"Δδ"=>"Delta2",
"Εε"=>"Epsilon",
"Ζζ"=>"Zeta",
"Ηη"=>"Eta",
"Θθ"=>"Theta",
"Ιι"=>"Iota"
];
echo "<p>Letters of the Greek Alphabet:</p>";
echo "<table>";
echo "<tr><th>Symbol</th><th>Name</th></tr>";
foreach($alphaGR as $symbol=>$name) {
echo "<tr><td>$symbol</td><td>$name</td></tr>";
}
echo "</table>";
?>
This example creates an HTML table containing character symbols from the Greek alphabet and their names. The resulting output looks like this:
An HTML table displaying letters from the Greek alphabet
We can also use a foreach loop to iterate over a multidimensional array. In an earlier example, we examined a script that created a two-dimensional array called $students containing the names of five students and their test results, and echoed the contents of the array to the screen, using a separate command to echo each student's test results.
For five students this is OK - up to a point. But what if we had fifty students? Or a hundred? Outputting the results one line of code at a time then becomes time consuming and extremely inefficient, not to mention tedious. A far better solution is to use a foreach loop to get the job done. We could do this, for example:
<?php
$students = [
["name"=>"Anderson, N", "score"=>51],
["name"=>"Beckham, D", "score"=>31],
["name"=>"Einstein, A", "score"=>99],
["name"=>"Foster, R", "score"=>95],
["name"=>"Miller, G", "score"=>75]
];
echo "Student Results:<br>";
foreach($students as $student) {
echo $student["name"] . ": " . $student["score"] . "<br>";
}
// Student Results:
// Anderson, N: 51
// Beckham, D: 31
// Einstein, A: 99
// Foster, R: 95
// Miller, G: 75
?>
This achieves exactly the same result as our earlier example but in a far more efficient manner. Of course, for higher-order multi-dimensional loops, we may have to use nested foreach loops, and things can become somewhat complicated, although not necessarily as complicated as you might imagine. We'll be exploring this topic in more detail in another article, but here is a (very) simple example of how we might use nested foreach loops to process a two-dimensional array holding a matrix:
<?php
$matrix = [
[25, 24, 31],
[47, 58, 86],
[17, 78, 99]
];
foreach ($matrix as $row) {
foreach ($row as $col) {
echo $col . " ";
}
echo "<br>";
}
// 25 24 31
// 47 58 86
// 17 78 99
?>
Unless blessed with a phenomenal memory, it will inevitably be the case with an array of any size that we cannot always be certain whether or not a particular element exists or, even if we know it exists, where it can be found within the array. Fortunately, PHP provides a number of functions that can aid us in this respect.
The first function we'll look at is in_array(). This function takes three arguments. The first is the value we are trying to find, and the second is the name of the array variable in which we are trying to find that value.
The third argument is a Boolean value that determine whether or not the comparison used to determine whether a value in the array matches the value we seek is strict or non-strict (i.e. whether the comparison is made using the identity operator (===) or the equality operator (==). This argument defaults to FALSE (non-strict).
If in_array() finds a value in the array matching its first argument, it returns TRUE, otherwise it returns FALSE. Let's look at an example of in_array() in action:
<?php
$trees = ["Oak", "Ash", "Beech", "Elm", "Sycamore", "Cedar", "Larch", "Maple"];
if(in_array("Cedar", $trees)) {
echo "Cedar is in the array!<br>";
}
else {
echo "Cedar is not in the array . . .<br>";
}
if(in_array("Redwood", $trees)) {
echo "Redwood is in the array!";
}
else {
echo "Redwood is not in the array . . .";
}
// Cedar is in the array!
// Redwood is not in the array . . .
?>
Note that in_array() is case-sensitive, so if we need to search for a string value on a case-insensitive basis we are going to have to change our approach slightly. We could, for example, do something like this:
<?php
$trees = ["Oak", "Ash", "Beech", "Elm", "Sycamore", "Cedar", "Larch", "Maple"];
if(in_array("cedar", array_map("strtolower", $trees))) {
echo "Cedar is in the array!<br>";
}
else {
echo "Cedar is not in the array . . .<br>";
}
if(in_array("redwood", array_map("strtolower", $trees))) {
echo "Redwood is in the array!";
}
else {
echo "Redwood is not in the array . . .";
}
// Cedar is in the array!
// Redwood is not in the array . . .
?>
What we have done here is to provide the string value we are searching to in_array() as an all lower-case string. We then apply the array_map() function to the array variable name passed to in_array() as its second argument, with the callback function argument for array_map() set to "strtolower". A detailed explanation of the array_map() function is a little outside the scope of this article, but the general idea is that it applies the strtolower() function to every element in the target array.
We can do something very similar using the array_search() function, which takes the same arguments as in_array(), with the third (Boolean) argument set to FALSE (non-strict comparison) by default. Like in_array(), array_search() returns FALSE if the search cannot find a match. Unlike in_array(), if the value being searched for is in the target array, array_search() returns the key of the first matching value. Here is an example:
<?php
$trees = ["Oak", "Ash", "Beech", "Elm", "Sycamore", "Cedar", "Larch", "Maple"];
$key = array_search("cedar", array_map("strtolower", $trees));
if($key) {
echo "Cedar is in the array!<br>";
}
else {
echo "Cedar is not in the array . . .<br>";
}
$key = array_search("redwood", array_map("strtolower", $trees));
if($key) {
echo "Redwood is in the array!";
}
else {
echo "Redwood is not in the array . . .";
}
// Cedar is in the array!
// Redwood is not in the array . . .
?>
This works, but there is a problem. The array_search() function may return Boolean FALSE, but it may also return a non-Boolean key value that evaluates to FALSE - for example a key of 0, or a key that is a negative integer. Modify the code in the above example to search for "oak" instead of "cedar" to see what happens. We can solve the problem by replacing this conditional statement:
if($key) {
// do something
}
with this one:
if($key!==FALSE) {
// do something
}
All we have done here is added a check to see whether or not the value returned really is the Boolean value FALSE, or simply a key value that evaluates to FALSE, by comparing it with FALSE using the non-identical comparison operator (!==).
Two more functions we should be aware of are isset() and array_key_exists(), both of which can be used to check whether a particular key exists within an array. The single argument passed to isset() is the name of an array variable followed immediately by the key being searched for within square brackets, i.e. isset($array["key"]).
The array_key_exists() function takes two arguments - the key to be searched for and the name of an array variable, i.e. array_key_exists("key", $array).
The other difference between array_key_exists() and isset() is that array_key_exists() always returns TRUE if the key is found in the target array, whereas isset() only returns TRUE if the key exists in the array and the stored value corresponding to it is not NULL. Both functions return FALSE if the key cannot be found in the target array. Here is an example that uses isset():
<?php
$primes = [2,3,5,7,11,13,17,19, NULL];
for($i = 0; $i < 10; $i++) {
if(isset($primes[$i])) {
echo "Element $i exists!<br>";
}
else {
echo "Element $i does not exist or is NULL<br>";
}
}
// Element 0 exists!
// Element 1 exists!
// Element 2 exists!
// Element 3 exists!
// Element 4 exists!
// Element 5 exists!
// Element 6 exists!
// Element 7 exists!
// Element 8 does not exist or is NULL
// Element 9 does not exist or is NULL
?>
And here is a similar example that uses array_key_exists():
<?php
$primes = [2,3,5,7,11,13,17,19, NULL];
for($i = 0; $i < 10; $i++) {
$key = array_key_exists($i, $primes);
if(array_key_exists($i, $primes)) {
echo "Element $i exists!<br>";
}
else {
echo "Element key $i does not exist<br>";
}
}
// Element 0 exists!
// Element 1 exists!
// Element 2 exists!
// Element 3 exists!
// Element 4 exists!
// Element 5 exists!
// Element 6 exists!
// Element 7 exists!
// Element 8 exists!
// Element 9 does not exist
?>
We can also traverse through an array using the array's own internal pointer, which always points to the current position within that array. The PHP array functions that enable us to do this are the reset(), end(), next() and prev() functions, all of which take the name of an array variable as their sole argument, adjust the array pointer to point to the first, last, next or previous element in the array respectively, and return the value stored in the array at that position. Consider the following example:
<?php
$primes = [2,3,5,7,11,13,17,19];
$currentVal = reset($primes);
while ($currentVal !== FALSE) {
echo "The current value is: $currentVal<br>";
$currentVal = next($primes);
};
// The current value is: 2
// The current value is: 3
// The current value is: 5
// The current value is: 7
// The current value is: 11
// The current value is: 13
// The current value is: 17
// The current value is: 19
?>
In this example, we created an array of prime numbers called $primes, and used the reset() function to set the array pointer to the start of the array and set the value of the variable $currentVal equal to the value of the first element in the array. We then looped forward through the array using a while loop, displaying the value of $currentVal and using the next() function to advance the array pointer by one on each iteration of the loop.
The exit condition for the while loop in this instance is that $currentVal should have the Boolean value FALSE. Because the next() and prev() functions both return FALSE when there are no more elements after the current element, the while loop terminates when the value of the last item in the array has been displayed, and the end of the array has been reached.
The two functions mentioned above which we have not yet showcased are the end() function and the prev() function, both of which we'll demonstrate now using the following script, which is fairly self-explanatory once you understand how the previous example works:
<?php
$primes = [2,3,5,7,11,13,17,19];
$currentVal = end($primes);
while ($currentVal !== FALSE) {
echo "The current value is: $currentVal<br>";
$currentVal = prev($primes);
};
// The current value is: 19
// The current value is: 17
// The current value is: 13
// The current value is: 11
// The current value is: 7
// The current value is: 5
// The current value is: 3
// The current value is: 2
?>
As we have stated several times, arrays are dynamic data structures. Creating an array is just the beginning of the story. We can add and remove elements, update existing elements, insert entire blocks of new elements into an array, or even merge several arrays together. There is a natural tendency for arrays to grow over time as new items are added, and the internal ordering of the array elements can be somewhat arbitrary.
Complicating things somewhat is the fact that PHP, for the most part, doesn't care whether the arrays are indexed or associative in nature. There is no real distinction between numeric indices and text-based keys. To PHP, they are all just keys, which means that even in indexed arrays, the index number allocated to an element does not necessarily reflect its overall position within the array.
This becomes an issue when we want to present array data in some user-friendly format to the world in general. People expect things to be in a particular order. League tables, for example, must be presented so that the individual or team with the most points appears at the top of the table, and the individual or team with the least points appears at the bottom. A computer, of course, doesn't care what order the data is in, so we have to make it care (so to speak).
Fortunately, PHP provides a number of built-in functions to assist us in this respect. The first function we'll look at is the sort() function, the name of which is a bit of a giveaway in terms of what it does! The sort() function takes two arguments - the name of the array variable to be sorted, and an optional flag argument that can be used to modify the function's behaviour. The return value is always TRUE. Here is an example of its use:
<?php
$trees = [
"Oak",
"Elm",
"Ash",
"Cedar"
];
echo "Trees, unordered:<br><br>";
foreach($trees as $tree) {
echo "$tree<br>";
}
echo "<br>Trees, ordered:<br><br>";
sort($trees);
foreach($trees as $tree) {
echo "$tree<br>";
}
// Trees, unordered:
//
// Oak
// Elm
// Ash
// Cedar
//
// Trees, ordered:
//
// Ash
// Cedar
// Elm
// Oak
?>
As you can see, the sort() function has sorted the array elements alphabetically, and in ascending order. We have not used the optional flag argument, but by default this is set to SORT_REGULAR. A brief summary of the flags that can be used with the sort() function is probably helpful at this point. The following descriptions are derived from the official PHP manual:
Most of the time, when using the sort() function, we will probably be using the default flag (SORT_REGULAR), so we can omit the flag argument. Comparing items normally in this case means sorting alpha-numerically. For example, if we have a mixed array containing both strings and numeric values, numeric values will appear before string values in the sorted list.
Before proceeding, we should probably point out that all of the array sorting functions we will discuss here return TRUE, and all of them take exactly the same arguments, i.e. the name of the array variable to be sorted and one of the optional flag arguments described above (if omitted, a default of SORT_REGULAR is assumed).
Numbers will appear in ascending numerical order, followed by strings in ascending alphabetical order. Note, however, that the sort() function is case-sensitive. Strings starting with an upper-case letter will appear before strings starting with a lower-case letter (we hinted at possible solutions to this problem when we talked about searching arrays).
The sort() function always sorts arrays in ascending order. In order to sort an array into descending order, we can use the rsort() function. This function works in similar fashion to sort(), but sorts the array in descending order. For example:
<?php
$trees = [
"Oak",
"Elm",
"Ash",
"Cedar"
];
echo "Trees, unordered:<br><br>";
foreach($trees as $tree) {
echo "$tree<br>";
}
echo "<br>Trees, ordered (descending):<br><br>";
rsort($trees);
foreach($trees as $tree) {
echo "$tree<br>";
}
// Trees, unordered:
//
// Oak
// Elm
// Ash
// Cedar
//
// Trees, ordered:
//
// Oak
// Elm
// Cedar
// Ash
?>
The ordering precedence for mixed arrays is also reversed. String values will appear before numeric values in the sorted list, and are sorted into descending alphabetical order. Because rsort() is also case-sensitive, strings starting with a lower-case letter will appear before strings starting with an upper-case letter. Numbers will appear last, in descending numerical order.
So far, we have only considered sorting indexed arrays, but we will also need to sort associative arrays on occasion. PHP provides four sort functions specifically designed to work with associative arrays. The first function we will look at is asort().
In the following example we create an associative array that stores the names of twelve European countries: the original signatories to the Maastricht Treaty, which came into effect in November 1993 and established the European Union (EU). The key in each case is the Alpha-2 (two-character) country code. We use the asort() function, which sorts by value, alphabetically and in ascending order:
<?php
$countries = [
"DE"=>"Germany",
"IE"=>"Ireland",
"GR"=>"Greece",
"ES"=>"Spain",
"FR"=>"France",
"DK"=>"Denmark",
"IT"=>"Italy",
"LU"=>"Luxembourg",
"BE"=>"Belgium",
"NL"=>"Netherlands",
"PT"=>"Portugal",
"GB"=>"United Kingdom"
];
asort($countries);
echo "EU Member States, 1993:<br><br>";
foreach($countries as $code=>$state) {
echo "$code - $state<br>";
}
// EU Member States, 1993:
//
// BE - Belgium
// DK - Denmark
// FR - France
// DE - Germany
// GR - Greece
// IE - Ireland
// IT - Italy
// LU - Luxembourg
// NL - Netherlands
// PT - Portugal
// ES - Spain
// GB - United Kingdom
?>
We can also sort an associative array by key, using the ksort() function, which sorts arrays alphabetically and in ascending order using keys. Here is an example:
<?php
$countries = [
"DE"=>"Germany",
"IE"=>"Ireland",
"GR"=>"Greece",
"ES"=>"Spain",
"FR"=>"France",
"DK"=>"Denmark",
"IT"=>"Italy",
"LU"=>"Luxembourg",
"BE"=>"Belgium",
"NL"=>"Netherlands",
"PT"=>"Portugal",
"GB"=>"United Kingdom"
];
ksort($countries);
echo "EU Member States, 1993:<br><br>";
foreach($countries as $code=>$state) {
echo "$code - $state<br>";
}
// EU Member States, 1993:
//
// BE - Belgium
// DE - Germany
// DK - Denmark
// ES - Spain
// FR - France
// GB - United Kingdom
// GR - Greece
// IE - Ireland
// IT - Italy
// LU - Luxembourg
// NL - Netherlands
// PT - Portugal
?>
This script is identical to the previous example except for the sort function used (ksort() has replaced asort()). The result is still a list of country codes and names, but the order ha changed somewhat because the country codes used as array keys do not have the same alphabetical ordering as the names of the countries stored in the array as values. As a result, Germany, Spain and the United Kingdom have all moved up in the array.
The complimentary functions to asort() and ksort() are arsort() and krsort() respectively, both of which sort associative arrays into descending order. This is what happens if we substitute arsort() for asort()in our earlier example:
<?php
$countries = [
"DE"=>"Germany",
"IE"=>"Ireland",
"GR"=>"Greece",
"ES"=>"Spain",
"FR"=>"France",
"DK"=>"Denmark",
"IT"=>"Italy",
"LU"=>"Luxembourg",
"BE"=>"Belgium",
"NL"=>"Netherlands",
"PT"=>"Portugal",
"GB"=>"United Kingdom"
];
arsort($countries);
echo "EU Member States, 1993:<br><br>";
foreach($countries as $code=>$state) {
echo "$code - $state<br>";
}
// EU Member States, 1993:
//
// GB - United Kingdom
// ES - Spain
// PT - Portugal
// NL - Netherlands
// LU - Luxembourg
// IT - Italy
// IE - Ireland
// GR - Greece
// DE - Germany
// FR - France
// DK - Denmark
// BE - Belgium
?>
As you can see, arsort() gives us the same list as asort(), but in the reverse order. You should by now be able to predict the result of replacing the ksort() function with krsort(), but for the sake of completeness, here is a script to demonstrate:
<?php
$countries = [
"DE"=>"Germany",
"IE"=>"Ireland",
"GR"=>"Greece",
"ES"=>"Spain",
"FR"=>"France",
"DK"=>"Denmark",
"IT"=>"Italy",
"LU"=>"Luxembourg",
"BE"=>"Belgium",
"NL"=>"Netherlands",
"PT"=>"Portugal",
"GB"=>"United Kingdom"
];
krsort($countries);
echo "EU Member States, 1993:<br><br>";
foreach($countries as $code=>$state) {
echo "$code - $state<br>";
}
// EU Member States, 1993:
//
// PT - Portugal
// NL - Netherlands
// LU - Luxembourg
// IT - Italy
// IE - Ireland
// GR - Greece
// GB - United Kingdom
// FR - France
// ES - Spain
// DK - Denmark
// DE - Germany
// BE - Belgium
?>
As expected, the krsort() function produces the same list as ksort(), but in the reverse order.
The last function we want to introduce here is actually not an array sorting function at all in the sense that it does nor sort an array into alpha-numeric order, either ascending or descending. We refer, in fact, to the shuffle() function, which as its name suggests sorts an array into a random order. The shuffle() function takes a single argument - the name of an array variable - and always returns TRUE. Here is an example:
<?php
$pack = [
"♠A","♠2","♠3","♠4","♠5","♠6","♠7","♠8","♠9","♠X","♠J","♠Q","♠K",
"♥A","♥2","♥3","♥4","♥5","♥6","♥7","♥8","♥9","♥X","♥J","♥Q","♥K",
"♦A","♦2","♦3","♦4","♦5","♦6","♦7","♦8","♦9","♦X","♦J","♦Q","♦K",
"♣A","♣2","♣3","♣4","♣5","♣6","♣7","♣8","♣9","♣X","♣J","♣Q","♣K"
];
shuffle($pack);
$players = [[],[],[],[]];
echo "Bridge Hands:<br><br>";
$i = 0;
while($i < 52) {
for($j = 0; $j < 4; $j++) {
$card = $pack[$i];
array_push($players[$j], $card);
$i++;
}
}
for($i = 0; $i < 4; $i++) {
sort($players[$i]);
echo "Player " . ($i +1) . ": ";
for($j = 0; $j < 13; $j++) {
echo $players[$i][$j];
if($j < 12) {
echo ", ";
}
}
echo "<br><br>";
}
// Bridge Hands:
//
//
// Player 1: ♠4, ♠5, ♠7, ♠K, ♠X, ♣6, ♣9, ♣J, ♥8, ♥J, ♥X, ♦1, ♦J
//
// Player 2: ♠1, ♠6, ♠A, ♠Q, ♣2, ♣4, ♣Q, ♥5, ♦5, ♦6, ♦7, ♦K, ♦X
//
// Player 3: ♠3, ♠8, ♠J, ♣3, ♣8, ♣X, ♥2, ♥6, ♥7, ♦2, ♦3, ♦9, ♦Q
//
// Player 4: ♠2, ♣5, ♣7, ♣A, ♥3, ♥4, ♥9, ♥A, ♥K, ♥Q, ♦4, ♦8, ♦A
?>
In this example, we create an array of fifty-two elements representing the cards in a pack of cards, so for example "♦A" is the Ace of Spades, "♣3" is the three of Clubs, and so on. We use the shuffle() function to shuffle the order of the cards in the pack into a random order. We also create a two-dimensional array called $players that holds four elements, each of which is the empty array.
We then use a for loop inside a while loop (more about while loops in the next article) to populate each sub-array within the $players array with thirteen "cards" from the randomly sorted $pack array using the array_push() function. The last part of the program uses a for loop nested inside another for loop to sort each sub-array using sort(), and output the contents of each to the screen.
There are various reasons why we might want to compare arrays. We might, for example, use one array to store the list of items on a purchase order, and another array to store a list of the goods actually received against that order. A comparison of these two arrays would tell us whether of not all items ordered have been received. If the comparison indicates that the array contents match, we can conclude that the order is complete. If not, we can investigate further.
PHP provides a number of array operators and functions that can be used to compare two arrays. Well start by looking at how we might carry out a simple test for equality. Consider the following example:
<?php
$items01 = ["UK1234", "UK5678", "UK9876", "UK5432"];
$items02 = ["UK5432", "UK5678", "UK9876", "UK1234"];
if( $items01 == $items02 ) {
echo "Match";
}
else {
echo "No match";
}
// No match
sort($items01);
sort($items02);
echo "<br><br>";
if( $items01 == $items02 ) {
echo "Match";
}
else {
echo "No match";
}
//
// Match
?>
In this example we create two indexed arrays ($items01 and $items02) that contain the same elements, but in a different order. The first time we compare them using the equality operator, they are found not to be equal and we get the message "No match". We then sort both arrays using the sort() function, and this time when we test for equality the arrays are found to be equal and we get the message "Match".
What the above example highlights is that indexed arrays can contain exactly the same elements but still not be considered equal if the ordering of the elements within each array is different. It is therefore recommended, when comparing two indexed arrays, to sort them first.
The same problem does not arise when we are comparing associative arrays, as the following example demonstrates:
<?php
$greekAlphabet1 = ["Αα"=>"Alpha", "Ββ"=>"Beta", "Γγ"=>"Gamma", "Δδ"=>"Delta"];
$greekAlphabet2 = ["Δδ"=>"Delta", "Ββ"=>"Beta", "Γγ"=>"Gamma", "Αα"=>"Alpha"];
if($greekAlphabet1 == $greekAlphabet2) {
echo "Match";
}
else
{
echo "No match";
}
// Match
?>
Why does this problem arise with indexed arrays and not associative arrays? Actually, the answer is fairly straightforward. Array comparison is carried out on the basis that two arrays are the same if they contain the same elements, regardless of order. But for two elements to match they must have the same key-value pairing.
For an associative array, the key of any element within the array is independent of its position in the array, and will remain the same even if the array is sorted or has its elements reordered by other means. This is not the case for indexed arrays.
The order in which elements are inserted into an indexed array will determine the index number of each element, And, since PHP sees numeric indices as keys, two otherwise identical elements in two arrays will have different keys if they occupy different positions within their respective arrays, and will therefore not be considered to be equal.
Something else that can cause misleading results is the presence of a Boolean value in an array. Consider this example:
<?php
$primes1 = array(2, 3, 5, 7, 11);
$primes2 = array(TRUE, 3, 5, 7, 11);
if($primes1 == $primes2) {
echo "Match";
}
else {
echo "No match";
}
// Match
?>
Clearly something is wrong here. We are being told that the arrays $primes1 and $primes2 are equal, but the first element in $primes1 has the integer value 2, and the first element in $primes2 has the Boolean value TRUE. The two elements are not even the same type.
What happens, however, is that the corresponding elements in each array are compared for equality. The first comparison carried out here is 2 == TRUE. When PHP compares an integer value to a Boolean value, it casts the integer value to a Boolean value. Any non-zero positive integer is cast to the Boolean value TRUE. Hence the result of the comparison is also TRUE.
We can ensure that this happens by using the identity operator (===) instead of the equality operator. For example:
<?php
$primes1 = array(TRUE, 3, 5, 7, 11);
$primes2 = array(2, 3, 5, 7, 11);
if($primes1 === $primes2) {
echo "Match";
}
else {
echo "No match";
}
// No match
?>
Any comparisons made using the identity operator will require the two elements being compared to be of the same value and type in order to evaluate to TRUE, so 2 === TRUE will yield a result of FALSE because 2 is an integer value and TRUE is a Boolean value.
Sometimes we want to know, not just whether or not two arrays are equal but what, if any, the difference between them is. PHP provides several functions that help us to accomplish just that. All of these functions compare either values or keys in a case-sensitive manner, and on a strict basis, i.e. using the identity operator (===).
The first function we will look at is array_diff(). This function takes the names of two or more array variables as its arguments, compares the first array with the other arrays, and returns a new array containing all of the elements from the first array that are not present in any of the other arrays. Comparisons are made using values only, and keys in the array are preserved. Here is an example of its use:
<?php
$eu1957 = [
"BE"=>"Belgium",
"FR"=>"France",
"DE"=>"Germany",
"IT"=>"Italy",
"LU"=>"Luxembourg",
"NL"=>"Netherlands",
];
$eu1973 = [
"BE"=>"Belgium",
"DK"=>"Denmark",
"FR"=>"France",
"DE"=>"Germany",
"IE"=>"Ireland",
"IT"=>"Italy",
"LU"=>"Luxembourg",
"NL"=>"Netherlands",
"GB"=>"United Kingdom"
];
$euNew1973 = array_diff($eu1973, $eu1957);
echo "New EU Members, 1973:<br><br>";
foreach($euNew1973 as $code=>$country) {
echo $code . " - " . $country . "<br>";
}
// New EU Members, 1973:
//
// DK - Denmark
// IE - Ireland
// GB - United Kingdom
?>
The array_diff_key() function does much the same thing as array_diff(), except that instead of comparing values, it compares keys. If we substitute array_diff_key() for array_diff() in the example above, we get exactly the same result, because the arrays being compared are associative arrays in which each element has a unique key, i.e. a two-character (Alpha-2) national country code defined by the ISO 3166 standard. It's a different story with indexed arrays, however. Consider the following example:
<?php
$eu1957 = [
"Belgium",
"France",
"Germany",
"Italy",
"Luxembourg",
"Netherlands",
];
$eu1973 = [
"Belgium",
"Denmark",
"France",
"Germany",
"Ireland",
"Italy",
"Luxembourg",
"Netherlands",
"United Kingdom"
];
$euNew1973 = array_diff_key($eu1973, $eu1957);
echo "New EU Members, 1973:<br><br>";
foreach($euNew1973 as $code=>$country) {
echo $code . " - " . $country . "<br>";
}
// New EU Members, 1973:
//
// 6 - Luxembourg
// 7 - Netherlands
// 8 - United Kingdom
?>
Here, we have used two arrays that contain the same values as those in the previous example, but implemented as numerically indexed arrays. As you can see, the comparison still produces a three-element array, but with the exception of the United Kingdom the countries listed were not new EU members in 1973. The lesson here is not to use array_diff_key() with numerically indexed arrays.
Another function that should only be used with associative arrays is the array_diff_assoc() function, which compares both values and the keys associated with each value. In order for two elements to be considered a match, both their values and their keys must be identical. Consider the following script:
<?php
$eu1957 = [
"BEL"=>"Belgium",
"FR"=>"France",
"DE"=>"Germany",
"ITA"=>"Italy",
"LU"=>"Luxembourg",
"NL"=>"Netherlands",
];
$eu1973 = [
"BE"=>"Belgium",
"DK"=>"Denmark",
"FR"=>"France",
"DE"=>"Germany",
"IE"=>"Ireland",
"IT"=>"Italy",
"LU"=>"Luxembourg",
"NL"=>"Netherlands",
"GB"=>"United Kingdom"
];
$euNew1973 = array_diff_assoc($eu1973, $eu1957);
echo "New EU Members, 1973:<br><br>";
foreach($euNew1973 as $code=>$country) {
echo $code . " - " . $country . "<br>";
}
// New EU Members, 1973:
//
// BE - Belgium
// DK - Denmark
// IE - Ireland
// IT - Italy
// GB - United Kingdom
?>
For this example, the list of new members joining the EU in 1973 is incorrect because both Belgium and Italy were among the six original members in 1957. The error occurs because, in the first array ($eu1957), we have given these two elements the three-character (Alpha-3) country code from the ISO 3166 standard, whereas for the second array ($eu1973), we have used the Alpha-2 codes throughout. If we amend the first array so that all of the country codes are Alpha-2 codes, our script will behave as expected.
As well as finding the difference between two (or more) arrays, we sometimes need to find the intersection of two arrays, i.e. a list of the elements they have in common. PHP provides three functions that we can use to find the intersection of two arrays. The first function we will look at is the array_intersect() function which, like the array_diff() function, compares two or more arrays on the basis of their stored values only.
The array_intersect() function takes the names of two or more array variables as its arguments and returns an array that contains only those values that exist in all of the arrays. Keys are preserved, but on the basis that if two elements have the same value but different keys, the key first key encountered is preserved. The following example demonstrates how we might use this function:
<?php
$sciFi2020 = [
"The Invisible Man",
"Tenet",
"Possessor",
"Bloodshot",
"The Midnight Sky",
"Underwater",
"Sputnik",
"Archive",
"Project Power",
"A Quiet Place Part II"
];
$horror2020 = [
"Sputnik",
"Relic",
"The Invisible Man",
"Possessor",
"Host",
"His House",
"Freaky",
"A Quiet Place Part II",
"The Hunt",
"Underwater"
];
$horrorSciFi2020 = array_intersect($sciFi2020, $horror2020);
echo "Sci-fi Horror Films of 2020:<br><br>";
foreach($horrorSciFi2020 as $index=>$film) {
echo $index . " - " . $film . "<br>";
}
// Sci-fi Horror Films of 2020:
//
// 0 - The Invisible Man
// 2 - Possessor
// 5 - Underwater
// 6 - Sputnik
// 9 - A Quiet Place Part II
?>
Here we have two arrays - $sciFi2020, which stores the titles of ten science-fiction films from 2020, and $horror2020, which stores the titles of ten horror films from the same year. Because of an overlap in film genres, some films are classed as both science-fiction and horror, and thus appear in both lists. We use the array_intersect() function here to extract the films that appear in both lists and create a new array ($horrorSciFi2020).
We have displayed the contents of the new array together with their indices to illustrate the way in which the array_intersect() function preserves the original index number of each value it stores in the new array.
The array_intersect_key() function works in the same way as the array_intersect() function except that instead of comparing values, it compares keys. Here is an example of its use:
<?php
$pl_1992 = ["ARS"=>"Arsenal","AVL"=>"Aston Villa",
"BBR"=>"Blackburn Rovers","CHE"=>"Chelsea",
"COV"=>"Coventry City","CRY"=>"Crystal Palace",
"EVE"=>"Everton","IPS"=>"Ipswich Town",
"LEE"=>"Leeds United","LIV"=>"Liverpool",
"MCI"=>"Manchester City","MUN"=>"Manchester United",
"MID"=>"Middlesbrough","NOR"=>"Norwich City",
"NFO"=>"Nottingham Forest","OLD"=>"Oldham Athletic",
"QPR"=>"Queens Park Rangers","SHU"=>"Sheffield United",
"SHW"=>"Sheffield Wednesday","SOU"=>"Southampton",
"TOT"=>"Tottenham Hotspur","WIM"=>"AFC Wimbledon" ];
$pl_2025 = ["ARS"=>"Arsenal","AVL"=>"Aston Villa",
"BOU"=>"Bournemouth","BRE"=>"Brentford",
"BHA"=>"Brighton & Hove Albion","BRN"=>"Burnley",
"CHE"=>"Chelsea","CRY"=>"Crystal Palace",
"EVE"=>"Everton","FUL"=>"Fulham",
"LEE"=>"Leeds United","LIV"=>"Liverpool",
"MCI"=>"Manchester City","MUN"=>"Manchester United",
"NEW"=>"Newcastle United","NFO"=>"Nottingham Forest",
"SUN"=>"Sunderland","TOT"=>"Tottenham Hotspur",
"WHU"=>"West Ham United","WOL"=>"Wolverhampton Wanderers"];
$plOriginals = array_intersect_key($pl_1992, $pl_2025);
echo "Premier League teams for the 2025/2026 season<br>";
echo "that were in the Premier League in 1992:<br><br>";
foreach($plOriginals as $key=>$team) {
echo $key . " - " . $team . "<br>";
}
// Premier League teams for the 2025/2026 season
// that were in the Premier League in 1992:
//
// ARS - Arsenal
// AVL - Aston Villa
// CHE - Chelsea
// CRY - Crystal Palace
// EVE - Everton
// LEE - Leeds United
// LIV - Liverpool
// MCI - Manchester City
// MUN - Manchester United
// NFO - Nottingham Forest
// TOT - Tottenham Hotspur
?>
Note that in this example, we would get exactly the same result with array_intersect() because the keys used for the football clubs in both arrays (these are the codes used by Reuters to identify sports teams) fall almost entirely into the same alphabetical ordering (the lone exception being WIM=>AFC Wimbledon).
The final PHP function we will mention here is the array_intersect_assoc() function, which finds the intersection of two or more arrays by comparing both the key and the value of each element to determine whether that element is present in all of the input arrays. This is essentially the most stringent comparison function. Only if both the keys and the values of two elements are identical will they be considered to match. Nevertheless, for the example above, if we replace array_intersect_key() with array_intersect_assoc() we will get the same outcome.