PHP Access Arrays

0
5KB

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 »
Pesquisar
Categorias
Leia mais
Outro
PHP - Escape Characters
Escape Character To insert characters that are illegal in a string, use an escape character. An...
Por PHP Tutorial 2024-05-17 07:32:36 0 6KB
Outro
PHP Associative Arrays
PHP Associative Arrays Associative arrays are arrays that use named keys that you assign to...
Por PHP Tutorial 2024-05-17 08:01:14 0 5KB
Outro
PHP echo and print Statements
With PHP, there are two basic ways to get output: echo and print. In this...
Por PHP Tutorial 2024-05-17 07:20:06 0 4KB
Outro
PHP Casting
Sometimes you need to change a variable from one data type into another, and sometimes you want a...
Por PHP Tutorial 2024-05-17 07:38:02 0 3KB
Outro
PHP Math
PHP has a set of math functions that allows you to perform mathematical tasks on numbers. PHP...
Por PHP Tutorial 2024-05-17 07:39:09 0 3KB