Table of Contents
To access an array item, you can refer to the index number for indexed arrays, and the key name for associative arrays.
Access an item by referring to its index number:
<h4>Access_item_by_index_number</h4>
<p>Access an item by referring to its index number:</p>
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo $cars[2];
?>
Result View Example
To access items from an associative array, use the key name:
<h4>Access_item_by_key_name</h4>
<p>To access items from an associative array, use the key name:</p>
<?php
$cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964);
echo $cars["year"];
?>
Result View Example
<h4>Double_or_Single_Quotes</h4>
<p>You can use both double and single quotes when accessing an array:</p>
<?php
$cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964);
echo $cars["model"];
echo "<br>";
echo $cars['model'];
?>
Result View Example
Array items can be of any data type, including function.
To execute such a function, use the index number followed by parentheses ():
<h4>Execute_a_Function_Item</h4>
<p>Execute a function item:</p>
<?php
function myFunction() {
echo "I come from a function!";
}
$myArr = array("Volvo", 15, myFunction());
$myArr[2]();
?>
Result View Example
Use the key name when the function is an item in a associative array:
<h4>Execute_function_by_key_name</h4>
<p>Execute function by referring to the key name:</p>
<?php
function myFunction() {
echo "I come from a function!";
}
$myArr = array("car" => "Volvo", "age" => 15, "message" => myFunction());
$myArr["message"]();
?>
Result View Example
To loop through and print all the values of an associative array, you can use a foreach loop, like this:
<h4>Loop_Through_an_Associative_Array</h4>
<p>Display all array items, keys and values:</p>
<?php
$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);
foreach ($car as $x => $y) {
echo "$x: $y <br>";
}
?>
Result View Example
To loop through and print all the values of an indexed array, you can use a foreach loop, like this:
<h4>Loop_Through_an_Indexed_Array</h4>
<p>Display all array items:</p>
<?php
$cars = array("Volvo", "BMW", "Toyota");
foreach ($cars as $x) {
echo "$x <br>";
}
?>
Result View Example
Document in project
You can Download PDF file.