PHP Arrays
Think of a PHP array as one variable with room for many values. Everything sits together under a single name, and you reach an individual value through its position number or through a name you gave it.
Array Example
Here $cars keeps three car names in one place, and count() reports how many there are:
Output: PHP script
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
PHP Array Types
PHP gives you three kinds of arrays, and the difference lies in how you reach the items:
- Indexed arrays - each item is found by a number
- Associative arrays - each item is found by a key you name yourself
- Multidimensional arrays - the items are themselves arrays, one or several
PHP Array Items
PHP does not restrict what you can put in an array. Strings and numbers are what you will see most often, yet an item could just as well be an object, a function or another array.
The types can also be mixed freely within one array.
Mixed Data Types
This array holds a string, an integer and a nested array side by side:
Output: PHP script
<?php
$myArr = array("Volvo", 15, ["apples", "bananas"]);
echo count($myArr);
?>
PHP Array Functions
Much of the power of PHP arrays comes from the functions built into the language for working with them.
One of the simplest is count(), which tells you how many items an array holds:
Every array function is documented in our PHP Array Reference.
Count Array Items
Find out how many items $cars contains:
Output: PHP script
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>