Refresh
this page because I am probably still making changes
to it.
Arrays in PHP are very similar in concept to arrays in other
languages, but probably most similar to arrays in JavaScript.
This lesson will go over the basic syntax of creating, accessing,
and iterating through arrays, and also some useful array operators
and functions.
Arrays in PHP are very similar to arrays in other languages.
Each element contains one value
and each element is identified by its index or
subscript. However,
in PHP, arrays are Maps: they are a series of key-value
pairs, where the key is the array index and the
value is the element value. This means that you can use
any unique integer or string as your key/index. The actual
element value can be anything.
Creating Arrays
There are a few different ways to create an array in PHP:
This first example creates an array of values using the array()
construct:
The above example creates an array with some numbers, and then
uses that array to create an array with the square roots of those
numbers called $roots. The key of $roots is the number and the
value is the square root of the number. When you look inside
the $roots array using var_dump(), you see output similar to
this:
Notice that we use the count() function to get the number
of elements in the array, or the size or length of the array. In other
languages, you're probably used to doing this with some kind of array
or collection property or method, but in PHP you use count($arrayName),
where $arrayName is the variable that contains the array.
Accessing Elements
You can access individual array elements by specifying the index in square
brackets:
Note that if you have error/warnings turned on, you will see warnings about
using undefined offset/index.
Another interesting thing to note about arrays is that if you access
an element on an array that you haven't defined yet, PHP will create the array
for you and then add the element:
<?php
$foo["bar"] = 77;
var_dump($foo);
?>
This example's output shows that the array has on element with a
key of "bar" that contains the value 77:
array(1) {
["bar"]=> int(77)
}
The Foreach Loop
The foreach loop provides an easy way to loop through an array (and
you can also use it to traverse the properties of an object, as
you'll see in a later lesson).
There are two syntaxes you can use for the foreach loop.
The first version is:
foreach(array_expr as $value) {
statement(s) to repeat for each $value in the array expression
}
array_expr is the array, or an expression that yields an array, and
$value is the parameter that contains each array element in each
iteration.
For example, to print all the elements of the $languages array:
This example displays the contents of the $languages array inside
an unordered list.
That first version of the foreach syntax is useful if you're using standard,
sequential numeric indexes. However, if you're using other unique values
as keys, such as strings or non-sequential numbers, you will find the
second version of the foreach is more useful:
If you have keys that aren't sequential numbers starting from 0,
foreach(array_expr as $key => $value) {
statement(s) to repeat for each $key/$value pair in the array expression
}
As with the first version, array_expr is any array or any
expression that yields an array. The $key parameter contains
the name of an element's key and the $value paramter contains
the value associated with that specific $key.
Both versions of the foreach loop only allow for read-access to the array.
However, if you'd like to be able
to modify the $value and thus modify the array element inside
the foreach loop, prefix $value with the & ampersand character:
We add the unset($num) after the loop because of how references work:
after the loop, $num still references the last element value in
the array. If you change $num after the loop, you'll actually be
changing the last element in the array unintentionally. The
unset()
function destroys the $num variable so that it no longer references
the last array element.
A lot of your arrays in a program will be dynamic - the values might change
while the program is running. For example, you might be keeping a list of
items the user want's to purchase from an on-line store, and you would want
to be able to add items to the list and possibly even remove items from the
list (if the user changes his/her mind).
Adding Elements
As mentioned earlier, you can add an element to an array that
doesn't use sequential numeric indexes easily:
$myGrades["SYST10049"] = 99.0;
This will automatically add a new element to the end of the array,
using the key "SYST28043" and the value 99.0.
If the array uses a sequential numerical index, you saw earlier how a
statement such as
$languages[] = "Delphi";
will also add a new element to the end of an array.
Note that there are no elements 4, 5, and 6. Also note that the value "bbq"
is added to element 8. When using empty [] as the index to add a new
element, it is always added at the highest index + 1.
Removing Elements
The unset() function can be used to remove an element
from an array. Note that unset() does not adjust the array indexes.
This example demonstrates that when you remove an element from the
$example array, the rest of the elements don't shift to fill in the
empty space:
If you're familar with stack and queue operations such as push/pop/shift/unshift,
PHP has methods for these:
array_push(arrayName, element, element...)
will add one or more elements to the end of an array.
$variable = array_pop(arrayName)
remove the last element in the array and store it in $variable.
You can ignore the return value if you don't need to save it.
$variable = array_shift(arrayName)
removes the item from the beginning of the array and stores it in $variable.
You can ignore the return value if you don't need to save it.
array_unshift(arrayName, element, element...)
adds one or more elements to the beginning of the array.
If the array uses sequential, numeric indexes, the array elements will
be moved to fit any new element or to fill any space left by a
removed element. Otherwise, the elements' positions are unaffected.
Some operators can be used to perform operations on arrays:
Array Operators
Operation
Description
+
Union
==
Equality
===
Identical
!= or <>
Inequality
!==
Not Identical
The Union operator will result in the union
of the left-hand and right-hand array operands. If there are duplicate
keys/indexes, the left-hand elements will be used and the right-hand elements
will be ignored:
The third array $rooms contains the seven unique
elements between the two arrays $bigRooms and $labs.
Notice that the duplicates occur with the $bigRooms values: j222 is listed with the value
40, not 20; j322 is listed with the value 40, not 22.
The Equality operator will return true if
both the left-hand and right-hand array operands have the same keys/indexes
and values:
Our output shows that despite the array elements being in a different
order in each array, the two arrays are considered equal until we
change one of the array values:
bool(true)
bool(false)
The Identity operator only returns true if both arrays
have the exact same key-value pairs in the exact same order:
There are several functions you can use when working
with arrays. We don't have time to cover all of them, so make
sure you take the time to browse through them using the
link in the box up above. Here are some you'll find useful
in these tutorials. Be sure to check the manual for each
function and try out some examples.
Miscellaneous
array_rand() -
chooses an entry at random and returns the key for that entry
count() -
returns the number of elements in an array
Searching
array_key_exists() -
searches an array for a specific key and returns true if an
element with the specified key exists in the array, or false if the
element doesn't exist
in_array() -
checks to see if a value exists in the array, returns true if it exists
or false if it doesn't exist
array_search() -
searches the array for a specific value and returns the key if That
value exists in the array, otherwise it returns false (if the values are
strings, the search is case-sensitive)
Joining/Splitting
array_merge() -
merges one or more arrays by appending the elements of the next array
to the end of the previous array.
If the keys are strings and there are duplicate keys, a newly appended
element will overwrite the previous one.
If the keys are numeric and there are duplicate keys, the new value will
be appended with the next valid index and the rest of the elements will be
renumbered.
array_slice() - returns a copy of a set of contiguous
elements in the array
array_splice() - removes and returns a portion of the
array and replaces the removed elements with other elements
Processing
array_sum()
-
calculates and returns the sum of all the values in an array
as an int or a float value, or returns 1 if array is empty
array_product() - calculates and returns the product
of all the values in the array as int or float, or returns 0 if the
array is empty
shuffle() -
randomly changes the order of an array
array_unique() - returns a copy of an array but
with all the duplicate values removed
Sorting
asort() -
sorts an array by values in ascending order but keeps index associations
with each value
arsort() -
sorts an array by values in descending order but keeps index associations
ksort() -
sort an array by keys in ascending order
krsort -
sort an array by keys in descending order
sort() -
sorts an array by values in ascending order and reassigns the indexes
rsort() -
sorts an array by values in descending order and reassigns the indexes
Exercises
1. Write a program that creates an array called $primes
that contains all the prime numbers from 1 to 50. Display the array on the
page in the following format: