PHP Associative Arrays

This YouTube video was created by Steve Griffith.

What is an Associative Array

An associative array is similar to a simple array except that instead of using numbers to refer to each of the items, there is a word label for each.

Creating an Associative Array

Associative array can be created using the array() method or the array literal.

$person = array();
$person = [];

This creates a simple OR an associative array. The difference appears when you create the initial array with a set of parameters.

An associative array is created when the array value are initialize with a string as a key.

$person = array('id'=>123, 'name'=>'Oscar Leroy', 'email'=>'oscar@cornergas.com');
$person = ['id'=>123, 'name'=>'Oscar Leroy', 'email'=>'oscar@cornergas.com'];

The arrays above would have three items called "id", "name" and "email". We can use double or single quotes around the item labels or values. The equal sign and the greater than sign written together is the sign for assigning a value to an associative array element.

Accessing Values from an Associative Array

To output a value from an associative array we use the echo command along with the name of an array followed with the square brackets wrapped around the label for the item.

echo $person['name']; //would output Oscar Leroy

Adding and Updating Items to Associative Array Values

In order to add a new item to an associative array we must use a label inside of the square brackets so that there is a new label associated with the new value.

$person['age'] = 65;

If you want to update that value then you use the same syntax.

$person['age'] = 66;

Getting the Length of Associative Array

Just like with simple arrays, you can use the count() OR sizeof() function to get the length of an associative array.

echo sizeof( $person ); //outputs 4
echo count( $person ); //outputs 4