PHP 5 Arrays

Arrays can store multiple values in a single variable:


<?php $cars=array("Volvo","BMW","Toyota"); echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . "."; ?>

What is an array?

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), store it in a single variable, like this:

$ cars1 = "Volvo";
$ cars2 = "BMW";
$ cars3 = "Toyota";

However, what if you want to iterate through the array and find a specific one? What if the array has 300 items instead of 3?

The solution is to create an array!

Arrays can store multiple values in a single variable, and you can access the values in them based on the key.

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 numeric ID keys
  • Associative array -an array with the specified keys, each key is associated with a value
  • Multidimensional arrays -arrays containing one or more arrays

PHP numeric array

There are two ways to create a numeric array:

Automatically assign ID keys (ID keys always start at 0):

$ cars = array ("Volvo", "BMW", "Toyota");

Manually assign ID keys:


The following example creates a numeric array named $ cars, assigns three elements to the array, and prints a text containing the array values:


<?php $cars=array("Volvo","BMW","Toyota"); echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . "."; ?>

Get the length of the array-count () function

count () function returns the length of the array (the number of elements):


<?php $cars=array("Volvo","BMW","Toyota"); echo count($cars); ?>

Iterating through numeric arrays

Iterate and print all the values in the numeric array, you can use a for loop as follows:


<?php $cars=array("Volvo","BMW","Toyota"); $arrlength=count($cars); for($x=0;$x<$arrlength;$x++) { echo $cars[$x]; echo "<br>"; } ?>

PHP associative array

Associative arrays are arrays that use the specified keys you assigned to the array.

There are two ways to create associative arrays:




The specified keys can then be used in the script:


<?php $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); echo "Peter is " . $age['Peter'] . " years old."; ?>

Iterating through associative arrays

Iterate and print all the values in the associative array, you can use a foreach loop as follows:


<?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 covered in detail in the PHP Advanced Tutorial section.

The complete PHP Array reference manual

For a complete reference manual of all array functions, please visit our PHP Array Reference Manual

This reference manual provides a brief description and application examples of each function!