Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

Create Arrays

Create Array

You can create arrays using the array() function:

Example

$cars = array("Volvo", "BMW", "Toyota");

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

Example

$cars = ["Volvo", "BMW", "Toyota"];

Multiple Lines

Line breaks are not significant, allowing an array declaration to span multiple lines:

Example

$cars = [
 "Volvo",
 "BMW",
 "Toyota"
];

Trailing Comma

A comma after the last item is permissible:

Example

$cars = [
 "Volvo",
 "BMW",
 "Toyota",
];

Array Keys

When creating indexed arrays, keys are assigned automatically, starting at 0 and increasing by 1 for each item. Therefore, the array above could also be defined with explicit keys:

Example

$cars = [
 0 => "Volvo",
 1 => "BMW",
 2 =>"Toyota"
];

As you can see, indexed arrays are similar to associative arrays, but associative arrays use names instead of numbers:

Example

$myCar = [
  "brand" => "Ford",
  "model" => "Mustang",
  "year" => 1964
];

Declare Empty Array

 

You can create an empty array initially and add items to it later:

Example

$cars = [];
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";

The same applies to associative arrays; you can declare the array first and then add items to it later:

Example

$myCar = [];
$myCar["brand"] = "Ford";
$myCar["model"] = "Mustang"
$myCar["year"] = 1964;

Mixing Array Keys

You can have arrays that contain both indexed and named keys:

Example

$myArr = [];
$myArr[0] = "apples";
$myArr[1] = "bananas";
$myArr["fruit"] = "cherries";