PHP Access Arrays

0
5K

Access Array Item

To access an array item, you can refer to the index number for indexed arrays, and the key name for associative arrays.

ExampleGet your own PHP Server

Access an item by referring to its index number:

$cars = array("Volvo", "BMW", "Toyota");
echo $cars[2];
Try it Yourself »

Note: The first item has index 0.

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

Example

Access an item by referring to its key name:

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

Double or Single Quotes

You can use both double and single quotes when accessing an array:

Example

echo $cars["model"];
echo $cars['model'];
Try it Yourself »

Excecute 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 ():

Example

Execute a function item:

function myFunction() {
  echo "I come from a function!";
}

$myArr = array("Volvo", 15, myFunction);

$myArr[2]();
Try it Yourself »

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

Example

Execute function by referring to the key name:

function myFunction() {
  echo "I come from a function!";
}

$myArr = array("car" => "Volvo", "age" => 15, "message" => myFunction);

$myArr["message"]();
Try it Yourself »

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:

Example

Display all array items, keys and values:

$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);

foreach ($car as $x => $y) {
  echo "$x: $y <br>";
}
Try it Yourself »

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:

Example

Display all array items:

$cars = array("Volvo", "BMW", "Toyota");
foreach ($cars as $x) {
  echo "$x <br>";
}
Try it Yourself »
Cerca
Categorie
Leggi tutto
Altre informazioni
PHP - Modify Strings
PHP has a set of built-in functions that you can use to modify strings. Upper Case...
By PHP Tutorial 2024-05-17 07:29:19 0 5K
Altre informazioni
PHP foreach Loop
The foreach loop - Loops through a block of code for each element in an array or each...
By PHP Tutorial 2024-05-17 07:50:19 0 3K
Altre informazioni
PHP Magic Constants
PHP Predefined Constants PHP has nine predefined constants that change value depending on where...
By PHP Tutorial 2024-05-17 07:40:16 0 2K
Altre informazioni
PHP Sorting Arrays
The elements in an array can be sorted in alphabetical or numerical order, descending or...
By PHP Tutorial 2024-05-17 08:06:46 0 5K
Altre informazioni
PHP Syntax
A PHP script is executed on the server, and the plain HTML result is sent back to the browser....
By PHP Tutorial 2024-05-17 07:10:53 0 4K