Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

Access Array Item

Access Array Item

To access an array item, use the index number for indexed arrays and the key name for associative arrays.

Example

Access an item by using its index number:

$cars = array("Volvo", "BMW", "Toyota");
echo $cars[2];
Note: The first item has an index of 0.

To access items in an associative array, use the key name:

Example

Access an item by using its key name:

$cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964);
echo $cars["year"];

Double or Single Quotes

You can use either double or single quotes when accessing an array:

Example

echo $cars["model"];
echo $cars['model'];

Excecute a Function Item

Array items can be of any data type, including functions.

To execute a function stored in an array, use the index number followed by parentheses ( ):

Example

Call a function item:

function myFunction() {
 echo "I come from a function!";
}
$myArr = array("Volvo", 15, myFunction);

$myArr
[2]();

Use the key name when the function is an item in an associative array:

Example

Call a function by referring to its key name:

  function myFunction() {
 echo "I come from a function!";
}
$myArr = array("car" => "Volvo", "age" => 15, "message" => myFunction);
$myArr["message"]();

Loop Through an Associative Array

To iterate through and print all the values of an associative array, you can use a foreach loop like this:

Example

Print all array items with their keys and values:

$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);
foreach ($car as $x => $y) {
 echo "$x: $y <br>";
}

Loop Through an Indexed Array

To iterate through and print all the values of an indexed array, you can use a foreach loop like this:

Example

Print all array items:

$cars = array("Volvo", "BMW", "Toyota");
foreach ($cars as $x) {
 echo "$x <br>";
}