PHP Access Array Items
How you read an item depends on the kind of array: an indexed array wants the item's index number, while an associative array wants its key name.
Example
Put the index number in square brackets to read that item:
Output: PHP script
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo $cars[2];
?>
Access Associative Array Item
Note: Counting starts at 0, so index 0 is the first item. That is why $cars[2] above gave the third car.
Associative arrays work the same way, except the key name goes between the brackets:
Example
Read the year item by naming its key:
Output: PHP script
<?php
$cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964);
echo $cars["year"];
?>
Double or Single Quotes
Key names in brackets may be written with either kind of quotes, double or single. Both lines below read the same item:
Example
Output: PHP script
<?php
$cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964);
echo $cars["model"];
echo $cars['model'];
?>
Execute a Function Item
Since an item can be any data type, it can be a function too.
Here the item holds the function's name. To call it, write the index number and then add parentheses ():
Example
Call the function stored at index 2:
Output: PHP script
<?php
function myFunction() {
echo "I come from a function!";
}
$myArr = array("Volvo", 15, "myFunction");
$myArr[2]();
?>
Example
With an associative array, the key name takes the place of the index:
Output: PHP script
<?php
function myFunction() {
echo "I come from a function!";
}
$myArr = array("car" => "Volvo", "age" => 15, "message" => "myFunction");
$myArr["message"]();
?>
Loop Through an Associative Array
A foreach loop is the way to go through an associative array and print every value it holds:
Example
Print each key together with its value:
Output: PHP script
<?php
$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);
foreach ($car as $x => $y) {
echo "$x: $y <br>";
}
?>
Loop Through an Indexed Array
Indexed arrays work with foreach too. It visits each item in turn, so you can print every value without touching the index numbers:
Example
Print each car on its own line:
Output: PHP script
<?php
$cars = array("Volvo", "BMW", "Toyota");
foreach ($cars as $x) {
echo "$x <br>";
}
?>