PHP array
Array can store multiple values in a single variable:
Examples
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
Running instance »
What arrays are?
An array is a special variable multiple values can be stored in a single variable.
If you have a list of items (for example: a list of car names), which is stored in a single variable, as follows:
$cars2="BMW";
$cars3="Toyota";
However, if you want to loop through the array and find a specific one? If the item array of more than three but 300 it?
The solution is to create an array!
Arrays can store multiple values in a single variable, and you can access the value based on the key.
Create an array in PHP
In PHP, array () function is used to create an array:
In PHP, there are three types of arrays:
- Numeric array - An array with a numeric ID key
- Associative array - An array with the keys specified a value associated with each key
- Multidimensional array - containing one or more arrays of arrays
PHP numeric array
There are two ways to create an array of numerical methods:
Automatically assigned ID key (key ID always starts at 0):
Artificial assigned ID keys:
$cars[1]="BMW";
$cars[2]="Toyota";
The following example creates a numeric array called $ cars and to assign an array of three elements, then print some text that contains an array of values:
Examples
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
Running instance »
Gets an array of length - count () function
count () function returns the length of the array (number of elements):
Numeric array traversal
Through and print all numeric values in the array, you can use a for loop, as follows:
Examples
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++)
{
echo $cars[$x];
echo "<br>";
}
?>
Running instance »
PHP associative array
Associative array is to use an array of the specified key you assigned to the array.
There are two ways to create associative arrays:
or:
$age['Ben']="37";
$age['Joe']="43";
You can then use the key specified in the script:
Examples
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
Running instance »
Traverse an associative array
Through and print all the values in an associative array, you can use the foreach loop, as follows:
Examples
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Running instance »
Multidimensional Arrays
Multidimensional arrays will be described in detail in the Advanced PHP tutorial section.
Complete PHP Array Reference
For a complete reference manual for all array functions, visit our PHP Array Reference Manual .
This reference manual provides a brief description of each function and application examples!