PHP Arrays
An array can store multiple values in a single variable:
Example
Run Example »
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 looks like this:
$cars1="Volvo";
$cars2="BMW";
$cars3="Toyota";
However, what if you want to loop through the array and find a specific one? What if the array has not just 3 items but 300?
The solution is to create an array!
An array can store multiple values in a single variable, and you can access its values by key.
Creating Arrays in PHP
In PHP, the array() function is used to create an array:
array();
In PHP, there are three types of arrays:
- Numeric arrays - An array with numeric ID keys
- Associative arrays - An array with specified keys, where each key is associated with a value
- Multidimensional Arrays - An array containing one or more arrays
PHP Numeric Arrays
There are two ways to create a numeric array:
Auto-assigned ID keys (ID keys always start from 0):
$cars=array("Volvo","BMW","Toyota");
Manually assigned ID keys:
$cars[0]="Volvo";
$cars[1]="BMW";
$cars[2]="Toyota";
The example below creates a numeric array named $cars, assigns three elements to the array, and then prints a piece of text containing the array values:
Example
Run Example »
Getting the Length of an Array - The count() Function
The count() function is used to return the length of an array (the number of elements):
Example
Run Example »
Looping Through Numeric Arrays
To loop through and print all the values in a numeric array, you can use a for loop, as shown below:
Example
" ; } ?>Run Example »
PHP Associative Arrays
An associative array is an array that uses the specified keys you assign to the array.
There are two ways to create an associative array:
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
or:
$age['Peter']="35";
$age['Ben']="37";
$age['Joe']="43";
The specified keys can then be used in the script:
Example
" 35 " , " Ben " => " 37 " , " Joe " => " 43 " ) ; echo " Peter is " . $age [ ' Peter ' ] . " years old. " ; ?>Run Example »
Looping Through Associative Arrays
To loop through and print all the values in an associative array, you can use a foreach loop, as shown below:
Example
" 35 " , " Ben " => " 37 " , " Joe " => " 43 " ) ; foreach ( $age as $x => $x_value ) { echo " Key= " . $x . " , Value= " . $x_value ; echo "" ; } ?>
Run Example »
Multidimensional Arrays
Multidimensional Arrays This will be covered in detail in the advanced PHP tutorial section.
Complete PHP Array Reference Manual
To view the complete reference manual for all array functions, please visit our PHP Array Reference Manual.
This reference manual provides a brief description and application example for each function!