PHP Create Arrays

0
3K

Create Array

You can create arrays by using the array() function:

ExampleGet your own PHP Server

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

You can also use a shorter syntax by using the [] brackets:

Example

$cars = ["Volvo", "BMW", "Toyota"];
Try it Yourself »

Multiple Lines

Line breaks are not important, so an array declaration can span multiple lines:

Example

$cars = [
  "Volvo",
  "BMW",
  "Toyota"
];
Try it Yourself »

Trailing Comma

A comma after the last item is allowed:

Example

$cars = [
  "Volvo",
  "BMW",
  "Toyota",
];
Try it Yourself »

Array Keys

When creating indexed arrays the keys are given automatically, starting at 0 and increased by 1 for each item, so the array above could also be created with keys:

Example

$cars = [
  0 => "Volvo",
  1 => "BMW",
  2 =>"Toyota"
];
Try it Yourself »

As you can see, indexed arrays are the same as associative arrays, but associative arrays have names instead of numbers:

Example

$myCar = [
  "brand" => "Ford",
  "model" => "Mustang",
  "year" => 1964
];
Try it Yourself »

Declare Empty Array

You can declare an empty array first, and add items to it later:

Example

$cars = [];
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
Try it Yourself »

The same goes for associative arrays, you can declare the array first, and then add items to it:

Example

$myCar = [];
$myCar["brand"] = "Ford";
$myCar["model"] = "Mustang";
$myCar["year"] = 1964;
Try it Yourself »

Mixing Array Keys

You can have arrays with both indexed and named keys:

Example

$myArr = [];
$myArr[0] = "apples";
$myArr[1] = "bananas";
$myArr["fruit"] = "cherries";
Try it Yourself »
Search
Categories
Read More
Other
PHP Variables
Variables are "containers" for storing information. Creating (Declaring) PHP Variables In...
By PHP Tutorial 2024-05-17 07:16:59 0 2K
Other
PHP Data Types
PHP Data Types Variables can store data of different types, and different data types can do...
By PHP Tutorial 2024-05-17 07:27:24 0 2K
Other
PHP Installation
What Do I Need? To start using PHP, you can: Find a web host with PHP and MySQL support...
By PHP Tutorial 2024-05-17 07:09:40 0 2K
Other
PHP if Operators
Comparison Operators If statements usually contain conditions that compare two values....
By PHP Tutorial 2024-05-17 07:45:46 0 2K
Other
PHP Access Arrays
Access Array Item To access an array item, you can refer to the index number for indexed arrays,...
By PHP Tutorial 2024-05-17 08:02:32 0 4K