Arrays, part 2


This is a second part of basics of PHP arrays.

As we learned before, there are two types of PHP arrays: array of values and associative array. In fact, an array of values is a special case of associative array. That's a type of array where all keys are integers, and form a continuous sequence which starts with 0. In the example below $array1 and $array2 are the same:

$array1 = ['Sam', 'Jennifer', 'Helga'];

$array2 =
    0 => 'Sam',
    1 => 'Jennifer',
    2 => 'Helga'

Whenever you break this rule when deal with an array of values (by adding a key-value pair or by removing some existing value), it considered further as a general associative array:

$array1 = [10, 4, 46, 'Hello', 0]; # Array of values
var_dump($array1); # General associative array

$array2 = [10, 4, 46, 'Hello', 0]; # Array of values
$array2['name'] = 'Sam';
var_dump($array2); # General associative array

There is a shorthand for inserting values at the end of an array:

$array = [5, 10];
$array[] = 'Hello'; # Inserts 'Hello' at the end of the array
var_dump($array); # $array holds now [5, 10, 'Hello']

To insert a key-value pair into associative array you just need to assign the value as if it already exists:

$person =
    'name' => 'Sam',
    'age'  => 19

$person['birthplace'] = 'Redtown';


PHP arrays maintain the order of appending elements. If you iterate them with foreach then you'll see the same order which elements were inserted into that array.

You can use key-value syntax with foreach for iterating an array of values:

$array = ['Sam', 'Jennifer', 'Helga'];

foreach($array as $n => $name)
    var_dump($n, $name);

You can use [] syntax to append elements to associative array. That's barely useful feature, still you should know about it. It works like that: [] operator will append a key-value pair of an integer key and a given value. What exactly key will we see in that pair? If there is no integer keys in the array then the new key will be 0. If there are some integer keys already then the new key will be equal to the larger integer key plus one:

$array =
    'foo' => 'bar'

$array[] = 'Sam';

var_dump($array); # $array is ['foo' => 'bar', 0 => 'Sam']
$array =
    9     => 2,
    'foo' => 'bar',
    3     => 'Hello'

$array[] = 'Sam';

var_dump($array); # $array is [9 => 2, 'foo' => 'bar', 3 => 'Hello', 10 => 'Sam']

In the next lesson about arrays we will review built-in PHP functions provided to deal with arrays.

Share this page:

Learning plan

How reference the same PHP values with different names
Most common and useful PHP built-in functions
The next portion of things you should learn about PHP types
11. Arrays, part 2
The second part of basics of PHP arrays
Things you should know to configure error reporting properly
How to split PHP script into pieces and include them into each other
14. Operators
We should learn all PHP operators in details before we could continue