Arrays in PHP

PHP allows you to use arrays, but PHP arrays are actually associative arrays. Though you can treat them as regular arrays and use contiguous integer indices, they are more flexible than that. Integer indices need to be contiguous or start at zero and you can use strings as indices. In addition, since PHP is dynamically typed, PHP arrays allow mixed types. An array has no fixed type and you can place different mixed types into the same array. PHP arrays are dynamic, so there is no memory management or allocation/deallocation of memory space. Arrays will grow and shrink automatically as you add and remove elements.

Creating Arrays

Since PHP is dynamically typed, you do not need to declare an array or specify a particular type of variable that it holds. However, there are several ways that you can initialize an array. To create an empty array, you can call the array() function. Optionally, you can provide an initial list of elements to insert into the array by providing the list of elements as arguments to the function.

//create an empty array:
$arr = array();

//create an array with elements 10, 20, 30:
$arr = array(10, 20, 30);

//create an array with mixed types:
$arr = array(10, 3.14, "Hello");

//get the first element:
$x = $arr[0]; //x has value 10

Indexes in PHP

PHP uses 0-based indexing so the first element will be in $arr[0], second element in $arr[1] and so on.

Strings as Indices

Since arrays in PHP are associative arrays, keys are not limited to integers. You can also use strings as keys to index elements.

$arr = array();
$arr[0] = 5;
$arr["foo"] = 10;
$arr["hello"] = "world";

print "value = " . $arr["hello"];

Note that strings that contain integer values will be type-juggled into their numeric values. For example, $arr["10"] = 3; will be equivalent to $arr[10] = 3;. However, strings containing floating point values will not be coerced but will remain as strings, $arr["3.15"] = 7; for example.

Non-Contiguous Indices

Another aspect of PHP associative arrays is that integer indices need not be contiguous. For example:

$arr = array();
$arr[0] = 10;
$arr[5] = 20;

The values at indices 1 through 4 are undefined and the array contains some “holes” in its indices.

Key-Value Initialization

Since associative arrays in PHP can be indexed by either integers or strings and need not be ordered or contiguous, we can use a special key-value initialization syntax to define not only the values, but the keys that map to those values when we initialize an array. The “double arrow,” => is used to denote the mapping.

$arr = array(
    "foo"   => 5,
    4       => "bar",
    0       => 3.14,
    "baz"   => "ten"
);

Useful Functions

There are dozens of useful functions PHP defines that can be used with arrays. We’ll only highlight a few of the more useful ones. First, the count() function can be used to compute how many elements are stored in the array.

$arr = array(10, 20, 30);
$n = count($arr); //n is 3

For convenience and debugging, a special function, print_r() allows you to print the contents of an array in a human-readable format that resembles the key-value initialization syntax above. For example:

$arr = array(
    "foo" => 5,
    4 => "bar",
    0 => 3.14,
    "baz" => "ten"
);
print_r($arr);

Output:

Array
(
    [foo] => 5
    [4] => bar
    [0] => 3.14
    [baz] => ten
)

Two other functions, array_keys() and array_values() return new zero-indexed arrays containing the keys and the values of an array respectively. Reusing the example above:

$keys = array_keys($arr);
$vals = array_values($arr);
print_r($keys);
print_r($vals);

Output:

Array
(
    [0] => foo
    [1] => 4
    [2] => 0
    [3] => baz
)
Array
(
    [0] => 5
    [1] => bar
    [2] => 3.14
    [3] => ten
)

Finally, you can use the equality operators, == and === to compare arrays. The first is the loose equality operator and evaluates to true if the two compared arrays have the same key-value pairs while the second is the strict equality operator and is true only if the arrays have the same key/value pairs in the same order and are of the same type.

Iterating over Arrays

If we have an array in PHP that we know is 0-indexed and all elements are contiguous, we can use a normal for loop to iterate over its elements by incrementing an index variable.

for($i=0; $i<count($arr); $i++) {
    print $arr[$i] . "\n";
}

This fails, however, when we have an associative array that has a mix of integer and string keys or “holes” in the indexing of integer keys. For this reason, it is more reliable to use foreach loops. There are several ways that we can use a foreach loop. The most general usage is to use the double arrow notation to iterate over each key-value pair.

//for each key value pair:
foreach($arr as $key => $val) {
    print "$key maps to $val \n";
}

This syntax gives you access to both the key and the value for each element in the array $arr. The keyword as is used to denote the variable names $key and $val that will be changed on each iteration of the loop. You need not use the identifiers $key and $val ; you can use any legal variable names for the key/value variables. If you do not need the keys when iterating, you can use the following shorthand syntax.

//for each value:
foreach($arr as $val) {
print "$val \n";
}

Adding Elements

You can easily add elements to an array by providing an index and using the assignment operator as in the previous examples. There are also several functions PHP defines that can insert elements to the beginning (array_unshift()), end (array_push()) or at an arbitrary position (array_splice()).

$arr = array(10, 20, 30);

array_unshift($arr, 15);
//arr is now [15, 10, 20, 30]

array_push($arr, 25);
//arr is now [15, 10, 20, 30, 25]

//insert 35 at index 3:
array_splice($arr, 3, 0, 35);
//arr is now [15, 10, 20, 35, 30, 25]

Another, simpler way of adding elements is to use the following syntax:

$arr = array(10, 20, 30);
$arr[] = 5;
$arr[] = 15;
$arr[] = 25;
print_r($arr);

By using the assignment operator but not specifying the index, the element will be added to the next available integer index. Since there were already 3 elements in the array, each subsequent element is inserted at index 3, 4, and 5 respectively. In general, the element will be inserted at the maximum index value already used plus one. The example above results in the following:

Array
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 5
    [4] => 15
    [5] => 25
)

Removing Elements

You can remove elements from an array using the unset() function. This function only removes the element from the array, it does not shift other elements down to fill in the unused index.

$arr = array(10, 20, 30);
unset($arr[1]);
print_r($arr);

This example would result in the following:

Array
(
    [0] => 10
    [2] => 30
)

Further, you can use unset() to destroy all elements in the array: unset($arr); destroys the entire array. It does not merely empty the array, but it unsets the variable $arr itself.

Using Arrays in Functions

By default, all arguments to a function in PHP are passed by value; this includes arrays. Thus, if you make any changes to an array passed to a function, the changes are not realized in the calling function. You can explicitly specify that the array parameter is passed by reference so that any changes to the array are realized in the calling function. To illustrate, consider the following example.

function setFirst($a) {
    $a[0] = 5;
}

$arr = array(10, 20, 30);
print_r($arr);
setFirst($arr);
print_r($arr);

This example results in the following:

Array
(
    [0] => 10
    [1] => 20
    [2] => 30
)
Array
(
    [0] => 10
    [1] => 20
    [2] => 30
)

That is, the change to the first element does not affect the original array. However, if we specify that the array is passed by reference, then the change is realized. For example:

function setFirst(&$a) {
    $a[0] = 5;
}

$arr = array(10, 20, 30);
print_r($arr);
setFirst($arr);
print_r($arr);

This now results in the original array being changed:

Array
(
    [0] => 10
    [1] => 20
    [2] => 30
)
Array
(
    [0] => 5
    [1] => 20
    [2] => 30
)

Multidimensional Arrays

PHP supports multidimensional arrays in the sense that elements in an array can be of any type, including other arrays. We can use the same syntax and operations for single dimensional arrays. For example, we can use the double arrow syntax and assign arrays as values to create a 2-dimensional array.

 $mat = array(
    0 => array(10, 20, 30),
    1 => array(40, 50, 60),
    2 => array(70, 80, 90)
 );
 print_r($mat);

Which results in the following:

Array
(
    [0] => Array
        (
            [0] => 10
            [1] => 20
            [2] => 30
        )
    [1] => Array
        (
            [0] => 40
            [1] => 50
            [2] => 60
        )
    [2] => Array
        (
            [0] => 70
            [1] => 80
            [2] => 90
        )
)

Licenses and Attributions


Speak Your Mind