Summary: in this tutorial, you will learn about PHP array. We will discuss about the indexed array and associative array, and show you various techniques to manipulate arrays.
Table of Contents
- 1 Introduction to PHP array
- 2 Creating arrays
- 3 Displaying arrays
- 4 Counting array elements
- 5 Testing if a variable is an array
- 6 Adding / Removing elements
- 7 Searching for array elements
- 8 Looping over arrays
- 9 Sorting Arrays
- 10 Merging arrays
- 11 Converting an indexed array into a list of variables
- 12 Converting between an array and a string
Introduction to PHP array
In PHP, an array is made up of elements that are related and shared the same characteristics. Each array’s element has a key and value.
The key in array can be a string or a number. You use a key to look up a value of an element. The value of an element can be a string, a number, a Boolean value, an object or even another array.
There are two types of arrays in PHP:
- Indexed array: each element of an indexed array is referred to using a numeric index.
- Associative array: each element of an associative array is referred to using a string. The associative array is also known as a map or hash.
Creating arrays
Unlike other programming languages such as C/C++, PHP does not require you to specify the size of array when you create it. PHP also does not require you to declare array variable before using it.
To create an array, you specify a key inside a pair of square brackets followed by array variable and assign a value to it as follows:
1 2 3 4 5 6 7 8 | <?php $languages[0] = 'English'; // array of languages $languages[1] = 'French'; // add the second element $languages[2] = 'German'; // add the third element echo $languages[0]; // display the first element echo $languages[1]; // display the second element echo $languages[2]; // display the third element |
We have defined an array of languages that contains three elements. It is an indexed array because the values of its elements are referred by numeric values. If we use numeric values as the keys of an array, we can omit them when we initialize it as follows:
1 2 3 4 | <?php $languages[] = 'English'; // array of languages $languages[] = 'French'; // add the second element $languages[] = 'German'; // add the third element |
To create an associative array, you need to specify the keys of its elements explicitly. The following example defines the colors
associative array:
1 2 3 4 | <?php $colors['red'] = '#FF0000'; $colors['green'] = '#00FF00'; $colors['blue'] = '#0000FF'; |
Creating arrays using array() function
PHP provides array()
function that creates an indexed or associate array. The following example creates the languages
array that contains three elements:
1 2 | <?php $language = array('English','French','German'); |
To create an associative array, we can use array()
function with explicit keys defined for each element as following:
1 2 3 4 | <?php $colors = array('red'=>'#FF0000', 'green'=>'#00FF00', 'blue'=>'0000FF'); |
From PHP 5.4, you can use short syntax []
instead of the array()
function, for example:
1 2 3 4 5 6 7 8 | <?php $color = [ red => '#FF0000', green => '#00FF00', blue => '#0000FF', ]; var_dump($color); |
Creating arrays using range() function
PHP provides the range()
function to help you create a range array and fill it with elements that are in a range of values. The following is the range()
function:
1 | range(int low,int high,[optional in step]) |
You specify the range with low
and high
values, and an optional parameter called step
that indicates the distance between element’s values. For example, to create an array of 10
integers, you can use the range()
function as follows:
1 2 | <?php $int_array = range(1,10); |
If you want to create an array that contains only even numbers from 2
to 10
, you can use the range()
function as follows:
1 2 | <?php $int_even = range(2,10,2); |
Displaying arrays
It is very handy to inspect an entire array using the print_r()
function. See the following example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <?php // displaying indexed array $languages = array('English','French','German'); echo '<pre>'; print_r($languages); echo '</pre>'; // displaying associative array $colors = array('red'=>'#FF0000', 'green'=>'#00FF00', 'blue'=>'0000FF'); echo '<pre>'; print_r($colors); echo '</pre>'; |
Another way to display more detail about arrays is using the var_dump()
function:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php // displaying indexed array $languages = array('English','French','German'); var_dump($languages); // displaying associative array $colors = array('red'=>'#FF0000', 'green'=>'#00FF00', 'blue'=>'0000FF'); var_dump($colors); |
Counting array elements
In order to find the number of elements in an array, you use the count()
function.
1 2 3 4 5 6 7 8 9 | <?php $int_array = range(1,20); echo 'The number of array elements:' . count($int_array) .'<br/>'; $book = array('title' => 'PHP tutorial', 'publisher' => 'zentut.com'); echo 'The number of array elements:' . count($book) .'<br/>'; |
Testing if a variable is an array
PHP provides you with a function named is_array()
that tests if the type of a variable is array. The is_array()
function returns true
if a variable is an array, otherwise it returns false
. Let’s take a look at the following example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?php $myarray = array("php","array","is cool"); if(is_array($myarray)) echo '$myarray is an array' . '<br/>'; else echo '$myarray is not an array' . '<br/>'; // $size = 3; if(is_array($size)) echo '$size is an array' . '<br/>'; else echo '$size is not an array' . '<br/>'; |
Adding / Removing elements
In order to add a new element to an array, you need to assign a value to the new element, by specifying either numeric or string index based on the array type.
1 2 3 4 5 6 7 8 9 | <?php // adding new elements using numerical index $commands[] = "Add"; $commands[] = "Remove"; // adding new elements using string index $states['CA'] = 'California'; $states['TA'] = 'Texas'; |
PHP also provides a built-in function array_push()
that adds one or more elements at the end of the array. The array_push()
function returns true
on success and false
on failure. See the following example:
1 2 3 4 5 6 | <?php $states[] = "New York"; array_push($states,'California','Texas'); var_dump($states); |
To add an element at the begin of an array, you can use the array_unshift()
function.
1 2 3 4 5 | <?php $states = array('California','Texas'); array_unshift($states,'New York'); var_dump($states); |
To remove the last element from an array, you use the the array_pop()
function. The array_pop()
function returns the removed element:
1 2 3 4 | <?php $states = array('California','Texas','New York'); $state = array_pop($states); echo $state; // $state = Texas |
Searching for array elements
Testing if the array contains an element
PHP provides the in_array()
function that checks whether an element is in array or not. You pass the element and array arguments to the function. If the element is found, the function returns true
otherwise it returns false
.
There is a third optional argument named strict
. If you pass this argument as true
, the function will check not only the value but also the data type of the element.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?php // init the arrays $salary = array(56000,72000,80000,120000); $elem = 120000; $another = "56000"; // check if(in_array($elem,$salary)) echo "$elem found in the array"; if(in_array($another,$salary,true)) echo "$another found in the array"; else echo "$another not found in the array"; |
The second check was failed because the array element is integer type while the element to check is string type.
Check if a key exists in the keys of an associative array
To check whether a key exists in an associative array, you use the array_key_exists()
function. The function returns true
if the key is found in the array, otherwise returns false
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?php // array of languages $languages = array( 'France' => 'French', 'England' => 'English', 'India' => 'Indian', 'China' => 'Chinese' ); if(array_key_exists('China',$languages)){ echo 'The array $languages contains key "China"'; } else{ echo 'The array $languages does not contain key "China"'; } if (array_key_exists('Germany', $languages)) { echo 'The array $languages contains key "Germany"'; }else { echo 'The array $languages does not contain key "Germany"'; } |
Getting keys and values in associative arrays
If you want to get a set of specific keys in an associative array, you can use the array_keys()
function. The array_keys()
function returns an array that contains all the keys of the array.
1 2 3 4 5 6 7 8 9 10 11 | <?php // array of languages $languages = array( 'France' => 'French', 'England' => 'English', 'India' => 'Indian', 'China' => 'Chinese' ); $country = array_keys($languages); print_r($country); |
If you want to get all values of an associative array, you use the array_values()
function.
1 2 3 4 5 6 7 8 9 10 11 | <?php // array of languages $languages = array( 'France' => 'French', 'England' => 'English', 'India' => 'Indian', 'China' => 'Chinese' ); $lang = array_values($languages); print_r($lang); |
Looping over arrays
PHP provides a very special kind of looping statement called foreach that allows you to loop over arrays. The foreach
statement only works with arrays and objects.
Looping over indexed arrays
In order to loop over an indexed array, you use the following syntax:
1 2 3 4 | <?php foreach ($array_expression as $value) { // process value here; } |
The following example loops over an index array of programming languages and display each element’s value:
1 2 3 4 5 6 7 8 | <?php $pl = array('PHP','Python','C/C++','C#','Java','Perl'); foreach ($pl as $p) { // process value here; echo $p . '<br/>'; } |
Loop over associative arrays
To loop over associative arrays, you use the following syntax:
1 2 3 | foreach ($array_expression as $key => $value) { // process key and value here; } |
The following example illustrates how to loop over the $address
associative array:
1 2 3 4 5 6 7 8 9 10 11 12 | <?php $address = array('street' => 'North First Street', 'city' => 'San Jose', 'state' => 'CA', 'country' => 'USA'); echo '<address>'; foreach ($address as $key => $value) { echo "$key:\t $value" . '<br/>'; } echo '</address>'; |
Sorting Arrays
Sorting indexed arrays
PHP provides a pair of functions that allow to sort indexed arrays: sort()
and rsort()
. The sort()
function sorts an index arrays in ascending order, while rsort()
function sorts an indexed array in descending order. To sort an indexed array, you need to pass the array to the function as the following example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?php $pl = array('PHP','Python','C/C++','C#','Java','Perl'); sort($pl); echo '<pre>'; print_r($pl); echo '</pre>'; rsort($pl); echo '<pre>'; print_r($pl); echo '</pre>'; |
Sorting associative arrays
To sort associative arrays, you use a pair of functions: asort()
and arsort()
.
- The
asort()
function sorts an associative array by its values in ascending order. - The
arsort()
function sorts an associative array by its values in descending order.
Both functions preserve the association between each element’s key and its value.
Notice that if you apply the sort()
or rsort()
function to an associative array, the associative array is converted into an indexed array therefore you lose the link between each element’s key and its value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?php $address = array('street' => 'North First Street', 'city' => 'San Jose', 'state' => 'CA', 'country' => 'USA'); // sort in ascending order asort($address); echo '<pre>'; print_r($address); echo '</pre>'; // sort in descending order arsort($address); echo '<pre>'; print_r($address); echo '</pre>'; |
To sort an associative array by its keys, we can use a pair of functions: ksort()
and krsort()
.
- The
ksort()
function sorts an associative array by its keys in ascending order. - The
krsort()
function sorts an associative array by its keys in descending order.
Let’s take a look at the following example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?php $address = array('street' => 'North First Street', 'city' => 'San Jose', 'state' => 'CA', 'country' => 'USA'); // sort its keys in ascending order ksort($address); echo '<pre>'; print_r($address); echo '</pre>'; // sort its keys in descending order krsort($address); echo '<pre>'; print_r($address); echo '</pre>'; |
Merging arrays
To merge 2 or more arrays into one array, you use the array_merge()
function. The following example demonstrates how to merge 2 integer arrays:
1 2 3 4 5 6 7 8 9 10 11 | <?php $a1 = range(1,3); $a2 = range(5,9); // merges two arrays $a = array_merge($a1,$a2); echo '<pre>'; print_r($a); echo '</pre>'; |
Converting an indexed array into a list of variables
PHP provides a very handy function named list()
that helps you convert an indexed array into a list of variables. The following example demonstrates how to use the list()
function.
1 2 3 4 5 6 7 8 | <?php $section = array('PHP tutorial','PHP array'); list($tutorial,$topic) = $section; echo $tutorial . '<br/>'; echo $topic . '<br/>'; |
Converting between an array and a string
Convert a string into an array
To convert a string into an array, you use the explode()
function. The explode()
function splits the string based on the specified delimiter and returns an array that contains elements, which are substrings produced by the splitting operation. The following example converts a string into an array using a comma ( ,
) as the delimiter. The result is an array of strings.
1 2 3 4 5 6 7 | <?php $fruits = 'orange,apple,mango,coconut'; $fruits_a = explode(',',$fruits); print_r($fruits_a); |
Convert an array into a string
You use the implode()
function to convert an array into a string as follows:
1 2 3 4 5 6 7 | <?php $fruits_a = array('orange','apple','mango','coconut'); $fruits = implode(',',$fruits_a); echo $fruits; |
In this tutorial, we have introduced you the PHP array and various built-in array functions that allows you manipulate arrays effectively.