PHP Arrays
Arrays can store multiple values in a single variable:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
What is an Array?
An array is a special variable that can store multiple values in a single variable.
If you have a list of items (for example, a list of car names), storing them in a single variable like this:
However, what if you want to loop through the array and find a specific one? What if the items in the array are not just 3 but 300?
The solution is to create an array!
An array can store multiple values in a single variable, and you can access the values by referring to an index number.
Creating an Array in PHP
In PHP, the array()
function is used to create an array:
In PHP, there are three types of arrays:
- Numeric Arrays - Arrays with a numeric ID key
- Associative Arrays - Arrays with named keys, where each key is associated with a value
- Multidimensional Arrays - Arrays containing one or more arrays
PHP Numeric Arrays
There are two ways to create numeric arrays:
Automatically assigning ID keys (ID keys always start at 0):
Manually assigning ID keys:
The following example creates a numeric array named $cars and assigns three elements to it, then prints a text containing the array values:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
Get The Length of an Array - The count() Function
The count()
function is used to return the length (number of elements) of an array:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
Loop Through a Numeric Array
To loop through and print all the values of a numeric array, you can use a for
loop, like this:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
for($x = 0; $x < $arrlength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
PHP Associative Arrays
Associative arrays are arrays that use named keys that you assign to them.
There are two ways to create associative arrays:
or:
You can then use the named keys in your script:
Example
<?php
$age = array("Peter" => "35", "Ben" => "37", "Joe" => "43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
Loop Through an Associative Array
To loop through and print all the values of an associative array, you can use a foreach
loop, like this:
Example
<?php
$age = array("Peter" => "35", "Ben" => "37", "Joe" => "43");
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Multidimensional Arrays
Multidimensional Arrays will be explained in detail in the PHP Advanced section.
Complete PHP Array Reference
For a complete reference of all array functions, go to our PHP Array Reference.
This reference contains a brief description and examples of use for each function!