Grouping Data Values with PHP Array Variables

By Richard Blum

Array variables allow you to group related PHP data values together in a list using a single variable name. You can then either reference the values as a whole by referencing the variable name or handle each data value individually within the array by referencing its place in the list.

PHP supports two types of arrays: numeric and associative.

Numeric

The standard type of array variable is the numeric array. With the numeric array, PHP indexes each value you store in the array with an integer value, starting at 0 for the first item in the array list.

The way to define an array is to use the PHP array() function in an assignment statement:

$myscores = array(100, 120, 115);

Just because the array is a numeric array, that doesn’t mean you’re restricted to storing only numeric values:

$myfamily = array("Rich", "Barbara", "Katie", "Jessica");

Starting in PHP version 5.4, you can also define an array using square brackets instead of the array() function:

$myscores = [110, 120, 115];

PHP references each value in the array using a positional number within square brackets after the variable name. The first element in the array is at position 0, the second at position 1, and so on.

For example, to retrieve the first value stored in the array, you’d use $myfamily[0], which would return the value Rich.

Associative

The associative array variable is similar to what other programming languages call a “dictionary.” Instead of using numeric indexes, it assigns a string key value to individual values in the list. You use the special => assignment operator to do that when you define the array:

$favs = array("fruit" => "banana", "veggie" => "carrot");

This array definition assigns the key value of fruit to the data value banana, and the key value veggie to the data value carrot. With associative arrays, to reference a data value you must specify the key value in the square brackets:

$favs["fruit"]

There is one thing to watch out for, though, when using associative array variables in your PHP code. For some reason, the echo statement has a hard time detecting associative array variables, so it needs some help from you.

When you use an associative array variable in an echo statement, it’s a good idea to enclose it in braces, like this:

echo "My favorite fruit is {$favs['fruit']}\n";

This separates out the associative array variable from the string, so the echo statement can properly process it. Also, notice that the problem with quotes pops up when using associative array variables inside the echo statement. Because you want the output to show the value of the associative array variable, you need to use double quotes for the echo statement string. That means you must use single quotes around the associative array variable key.