PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store
Related Articles

PHP A to ZCE: Arrays

This article is part of the series “PHP A to Zend Certified Engineer”. In PHP A to ZCE, I will take you through 26 different yet equally important topics that will help you become a Zend Certified Engineer. Even if you're not interested in sitting the ZCE-PHP exam, these topics will elevate your understanding of PHP to a whole new level and allow you to become the guru in your company. Read more about PHP A to Zend Certified Engineer...

Arrays in PHP are the most useful and versatile data structure available. In this article I cover all of the important points you need to know in order to leverage the power of arrays in PHP.

About Arrays

  • An array is a collection of 0 or elements
  • Each element can be any PHP type (including another array)
  • Arrays can have unlimited elements and unlimited depth (subject to server memory limit)
  • Every element in an array has a corresponding key. The key is used to refer to a specific element
  • Unlike other languages, you don't need to specify the size of an array: you can add or remove elements at any time
  • You can check if a variable is an array using is_array()
  • Array function reference

Types of Arrays

  • There are two types of arrays: indexed and associative
  • Indexed arrays have keys automatically assigned, starting from zero (0)
  • Associative arrays use keys that are manually specified
  • Typically a key in an associative array is some string value
  • An array can be a combination of indexed and associative keys.

Creating Arrays

  • An array is created using the array() keyword. The following code creates an empty array:
Listing 1 listing-1.php
<?php
    $myArray = array();
?>
  • You can specify initial elements when calling array()
  • Indexed elements require just a value:
Listing 2 listing-2.php
<?php
    $myArray = array(10, 20, 30);
?>
  • Associative elements are passed in the format 'key' => 'value':
Listing 3 listing-3.php
<?php
    $myArray = array(
        'a' => 'my string',
        'b' => array()
    );
?>
  • You can combine these when creating an array. The first element will have index of 0:
Listing 4 listing-4.php
<?php
    $myArray = array(1234, 'foo' => 'bar');
 
    /*
        array(
            0     => 1234,
            'foo' => 'bar'
        )
    */
?>
  • You can manually specify the index of values. PHP will automatically determine the next index. In the following example, the bar element will have an index of 11:
Listing 5 listing-5.php
<?php
    $myArray = array(10 => 'foo', 'bar');
 
    /*
        array(
            10 => 'foo',
            11 => 'bar'
        )
    */
?>

Adding Elements to Arrays

  • You can add automatically indexed elements using the [] operator:
Listing 6 listing-6.php
<?php
    $myArray = array();
    $myArray[] = 'foo';
?>
  • You can also use array_push() to add automatically indexed elements. The advantage of doing this is you can add multiple elements at once:
Listing 7 listing-7.php
<?php
    $myArray = array();
    $myArray[] = 10;
    $myArray[] = 20;
    $myArray[] = 30;
 
    // equivalent:
    $myArray = array();
    array_push($myArray, 10, 20, 30)
?>
  • You can specify the index when adding elements in this way. The key can be hard-coded or it can come from another variable:
Listing 8 listing-8.php
<?php
    $myArray = array();
    $myArray['foo'] = 'bar';
 
    $key = 'hello';
    $myArray[$key] = 'goodbye';
 
    /*
        array(
            'foo'   => 'bar',
            'hello' => 'goodbye'
        )
    */
?>
  • You can add an element to the beginning of an array using array_unshift(). Any numerically indexed elements will have their indexed shifted accordingly:
Listing 9 listing-9.php
<?php
    $myArray = array('foo');
 
    array_unshift($myArray, 'bar');
 
    /*
        array(
            0 => 'bar',
            1 => 'foo'
        )
    */
?>

Removing Elements from Arrays

  • You can call unset() on an element of the array to remove it:
Listing 10 listing-10.php
<?php
    $myArray = array('hello', 'foo' => 'bar');
 
    unset($myArray[0]); // remove the 'hello' value
    unset($myArray['foo']); // remove the 'bar' value
?>
  • You can remove the last element of an array using array_pop(). This will also return that element:
Listing 11 listing-11.php
<?php
    $myArray = array(10, 20, 30, 40);
 
    $last = array_pop($myArray);
 
    /*
        $last = 40
        $myArray = array(
            0 => 10,
            1 => 20,
            2 => 30
        )
    */
?>
  • You can remove the first element of an array using array_shift. This will also return the element and re-index the array:
Listing 12 listing-12.php
<?php
    $myArray = array(10, 20, 30, 40);
 
    $first = array_shift($myArray);
 
    /*
        $first = 10
        $myArray = array(
            0 => 20,
            1 => 30,
            2 => 40
        )
    */
?>

Counting Arrays

  • Use the count() function to determine the size of an array
  • Some people prefer sizeof() instead - this is an alias to count(). Whichever one you decide to use, be consistent.
Listing 13 listing-13.php
<?php
    $array1 = array(10, 20, 30, 40);
    $array2 = array();
 
    echo count($array1); // 4
    echo count($array2); // 0
?>

Combining Arrays

  • There are two main ways to combine arrays: the + operator (see array operators) and array_merge()
  • Adding two arrays appends values from the right-hand array to the left-hand array. For any elements that use the same key, the left-hand array's value is used:
Listing 14 listing-14.php
<?php
    $arr1 = array(1, 2, 3);
    $arr2 = array(2, 3, 4);
    $arr3 = array(2, 3, 'foo' => 4);
 
    print_r($arr1 + $arr2);
    /*
        array(
            0 => 1,
            1 => 2,
            2 => 3
        )
    */
 
    print_r($arr1 + $arr3);
    /*
        array(
            0     => 1,
            1     => 2,
            2     => 3,
            'foo' => 4
        )
    */
?>
  • Using array_merge() won't skip over duplicate numerical keys, but it will overwrite duplicate non-numerical keys:
Listing 15 listing-15.php
<?php
    $arr3 = array(2, 3, 'foo' => 4);
    $arr4 = array(2, 3, 'foo' => 5);
 
    $arr5 = array_merge($arr3, $arr4);
 
    /*
        array (
            0     => 2
            1     => 3
            'foo' => 5
            2     => 2
            3     => 3
        )
    */
?>

Searching Arrays

  • To see if given an element with a certain key exists in an array, use array_key_exists():
Listing 16 listing-16.php
<?php
    $myArray = array('foo' => 'bar');
 
    if (array_key_exists('foo', $myArray)) {
        // do something
    }
?>
  • You can also use isset(), but if the value is set to null then false is returned:
Listing 17 listing-17.php
<?php
    $myArray = array('foo' => null);
 
    array_key_exists('foo', $myArray); // true
    isset($myArray['foo']); // false
?>
  • You can check if a specific element exists in an array using in_array():
Listing 18 listing-18.php
<?php
    $arr = array(10, 20, 30);
 
    if (in_array(20, $arr)) {
        // do something
    }
?>
  • You can check if a specific element exists and determine its key using array_search()
  • If the element is not found false is returned. It is important to differentiate between false and an index of 0:
Listing 19 listing-19.php
<?php
    $arr = array(10);
 
    // this will return false
    $key1 = array_search(5, $arr);
 
    // this will return 0
    $key2 = array_search(10, $arr);
 
    if ($key2 == false) {
        // this code is incorrect!
    }
 
    if ($key1 === false) {
        // this code is correct
    }
?>

Sorting Arrays

  • There are many array sorting functions in PHP. Some allow you to specify a custom sorting callback
  • These functions modify the original array you pass to them (that is, they don't return a new array with the original untouched)
  • Summary of sort functions
  • Sorting callbacks (e.g. for usort()) accept two arguments: return -1 if the first argument should appear first in the sorted array, 1 if the second should appear first, or 0 if they are equal (order undefined):
Listing 20 listing-20.php
<?php
    function mySort($a, $b)
    {
        if ($a > $b) { return -1; }
        if ($b > $a) { return 1; }
 
        return 0;
    }
 
    $myArray = array(12, 15, 7, 84, 33);
 
    usort($myArray, 'mySort');
 
    /*
    array (
        0 => 84
        1 => 33
        2 => 15
        3 => 12
        4 => 7
    )
    */
?>

Looping Over Arrays

  • Easiest way to loop over arrays is foreach()
  • Each element in a foreach() is a copy (except for objects). That is, modifying the element has no effect on the original array.
Listing 21 listing-21.php
<?php
    $myArray = array('a' => 'Apple', 'b' => 'Banana');
 
    foreach ($myArray as $key => $value) {
        echo sprintf("%s=%s\n", $key, $value);
    }
 
    /*
        Output:
            a=Apple
            b=Banana
    */
?>
  • You can also use a for() loop
  • Small optimization: Calculate the size of the array ahead of time.
Listing 22 listing-22.php
<?php
    $myArray = array(10, 20);
 
    for ($i = 0, $size = count($myArray); $i < $size; $i++) {
        echo $myArray[$i] . "\n";
    }
?>
  • Using foreach() can be tricky for associative arrays. Loop over the keys instead (use array_keys() to retrieve the keys:
Listing 23 listing-23.php
<?php
    $myArray = array('a' => 'Apple', 'b' => 'Banana');
    $keys = array_keys($myArray);
 
    for ($i = 0, $size = count($keys); $i < $size; $i++) {
        $key = $keys[$i];
        $value = $myArray[$key];
 
        echo sprintf("%s=%s\n", $key, $value);
    }
?>

Other Useful Operations

  • array_slice(): Extract n elements starting from position x. Array equivalent of the string cuntion substr()
  • array_reverse(): Return an array with elements in reverse order. Original array is unmodified
  • array_filter(): Remove empty elements from array
  • array_diff(): Find the difference between arrays
  • array_keys(): Retrieve all keys in an array
  • array_values(): Return an indexed version of an array (convert an associative array to an indexed array)
  • array_sum(): Calculate the total of all values in an array
  • shuffle(): Randomize the order of an array
  • array_rand(): Retrieve 1 or more random keys from an array (if retrieving 2 or more then an array of random keys is returned).

Other Options

PHP A to ZCE: Arrays