PHP Access Arrays

Back to ACP page

Table of Contents

PHP 1 Access item by index number

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]; ?>

Example 1

Result View Example

PHP 2 Access_item_by_key_name

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"]; ?>

Example 2

Result View Example

PHP 3 Double or Single Quotes

<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']; ?>

Example 3

Result View Example

PHP 4 Execute a Function Item

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](); ?>

Example 4

Result View Example

PHP 5 Execute function by key name

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"](); ?>

Example 5

Result View Example

PHP 6 Loop Through an Associative Array

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>"; } ?>

Example 6

Result View Example

PHP 7 Loop Through an Indexed Array

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>"; } ?>

Example 7

Result View Example

Document

Document in project

You can Download PDF file.

Reference