PHP array() Function
The PHP array() function is used to create an array. In PHP, there are three types of arrays:
- Indexed arrays - Arrays with numeric index
- Associative arrays - Arrays with named keys
- Multidimensional arrays - Arrays containing one or more arrays
Syntax
array(values)
Parameters
values |
Required. Using "index => values", separated by commas, define index and values. index may be of type string or integer. When index is omitted, an integer index is automatically generated, starting at 0. If index is an integer, next generated index will be increased by 1.Note: When two identical index are defined, the last overwrite the first. |
Return Value
Returns an array of the parameters.
Example: creating an indexed array
The example below shows how to create an indexed array using this function.
<?php $arr = array('John', 25, 'London'); //displaying the array print_r($arr); //using array elements echo $arr[0]." is ".$arr[1]. " years old and lives in ".$arr[2]."."; ?>
The output of the above code will be:
Array ( [0] => John [1] => 25 [2] => London ) John is 25 years old and lives in London.
Example: creating an associative array
Consider the example below where this function is used to create an associative array.
<?php $arr = array('name' => 'John', 'age' => 25, 'city' => 'London'); //displaying the array print_r($arr); //using array elements echo $arr['name']." is ".$arr['age']. " years old and lives in ".$arr['city']."."; ?>
The output of the above code will be:
Array ( [name] => John [age] => 25 [city] => London ) John is 25 years old and lives in London.
Example: creating a two-dimensional array
The example below demonstrates how to create a two-dimensional array.
<?php $info = array( "colors" => array("red" => 1, "green" => 2, "blue" => 3), "numbers" => array(10, 20, 30), "gaps" => array("first", 5 => "second", "third") ); //displaying the array print_r($info); ?>
The output of the above code will be:
Array ( [colors] => Array ( [red] => 1 [green] => 2 [blue] => 3 ) [numbers] => Array ( [0] => 10 [1] => 20 [2] => 30 ) [gaps] => Array ( [0] => first [5] => second [6] => third ) )
Example: 1-based indexed array
The array() function can also be used to create 1-based indexed array as shown in the example below:
<?php $firstquarter = array(1 => 'JAN', 'FEB', 'MAR'); print_r($firstquarter); ?>
The output of the above code will be:
Array ( [1] => JAN [2] => FEB [3] => MAR )
Example: Accessing an array inside double quotes
A value from the array can be accessed inside double quotes by enclosing it between curly braces. See the example below:
<?php $arr = array('name' => 'John', 'age' => 25); //using array elements inside double quotes echo "{$arr['name']} is {$arr['age']} years old."; ?>
The output of the above code will be:
John is 25 years old.
❮ PHP Array Reference