Unlike scalar variables, which assign only a single value to a variable, an array variable can hold multiple values.
Arrays are useful for holding values from database queries or web form entries, where each field (also called a “key”) holds a specific value.
Let’s take a look at how we define some of the arrays we use in PHP.Numbered Arrays.
If the programmer does not specify a key for each value in the array, PHP automatically numbers the keys, starting from zero.
This code defines an array $arrMonths, with each month of the year as an element in the array.<?php $arrMonths = ‘January’; $arrMonths = ‘February’; $arrMonths = ‘March’; $arrMonths = ‘April’; ?>
The PHP interpreter automatically defines each key in the array with a number, starting from zero.<?php $arrMonths = ‘January’; $arrMonths = ‘February’; $arrMonths = ‘March’; $arrMonths = ‘April’; ?>
Another method of defining an array is to use the array function:<?php $arrMonths= array(‘January’, ‘February’, ‘March’, ‘April’); ?>
This function creates a numbered array in the same way as the enumerated elements in the example above.
In some instances, the programmer does not want each value associated to a number, but to a more descriptive key. Each of these descriptive keys needs to be associated with a value, hence the term “associative” array.
Just as with a numerical array, code authors can create an associative array one element at a time:<?php $arrBooks[‘Comic Books’] = ‘Superman’; $arrBooks[‘Science Fiction’] = ‘Dune’; $arrBooks[‘Fantasy’] = ‘The Hobbit’; $arrBooks[‘Horror’] = ‘Carrie’; ?>
The array function is also useful for creating associative arrays. The “=>” symbol ties the key phrase to the value.<?php $arrBooks = array( ‘Comic’ => ‘Superman’, ‘Science Fiction’ => ‘Dune’, ‘Fantasy’ => ‘The Hobbit’, ‘Horror’ => ‘Carrie’); ?>
Is It An Array?
If you’re not certain if a variable has the structure of an array, the is_array function can test the variable to see if it is an array.<?php $baseballTeams = array(‘Cardinals’,...