Create Arrays in PHP
You make an array in PHP by calling the array() function and listing the items inside it.
Example
Build $cars by calling array():
Output: PHP script
<?php
$cars = array("Volvo", "BMW", "Toyota");
?>
Short Syntax
Tip: Square brackets [] do the same job with less typing:
Example
The same kind of array, this time written with []:
Output: PHP script
<?php
$cars = ["Volvo", "BMW", "Toyota"];
?>
Multiple Lines
PHP does not care about line breaks here, so you are free to spread an array over several lines, which often makes it easier to read:
Example
Output: PHP script
<?php
$cars = [
"Volvo",
"BMW",
"Toyota"
];
?>
Trailing Comma
You may leave a comma after the final item, and PHP will accept it:
Example
Output: PHP script
<?php
$cars = [
"Volvo",
"BMW",
"Toyota",
];
?>
Array Keys
If you don't give an indexed array any keys, PHP assigns them for you: 0 for the first item, then one higher for each item after it. Spelling those keys out yourself produces exactly the same array as the earlier examples:
Example
Output: PHP script
<?php
$cars = [
0 => "Volvo",
1 => "BMW",
2 =>"Toyota"
];
?>
Example
Written this way, it is clear that the two kinds of array share one form. The only difference is that an associative array has names where an indexed array has numbers:
Output: PHP script
<?php
$myCar = [
"brand" => "Ford",
"model" => "Mustang",
"year" => 1964
];
?>
Declare Empty Array
An array doesn't have to be filled right away. Start with an empty one and put items in later:
Example
Output: PHP script
<?php
$cars = [];
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
?>
Example
Associative arrays allow this as well: create the empty array first, then assign each key in turn:
Output: PHP script
<?php
$myCar = [];
$myCar["brand"] = "Ford";
$myCar["model"] = "Mustang";
$myCar["year"] = 1964;
?>
Mixing Array Keys
A single array can use numeric keys and named keys at the same time:
Example
Output: PHP script
<?php
$myArr = [];
$myArr[0] = "apples";
$myArr[1] = "bananas";
$myArr["fruit"] = "cherries";
?>