Table of Contents
<h4>Create_Array</h4>
<p>You can create arrays by using the array() function:</p>
<?php
$cars1 = array("Volvo", "BMW", "Toyota");
var_dump($cars1);
?>
<hr>
<p>You can also use a shorter syntax by using the [] brackets:</p>
<?php
$cars2 = ["Volvo", "BMW", "Toyota"];
var_dump($cars2);
?>
Result View Example
<pre>
<?php
$cars = [
"Volvo",
"BMW",
"Toyota"
];
var_dump($cars);
?>
</pre>
Result View Example
<h4>Trailing_Comma</h4>
<p>A comma after the last item is allowed:</p>
<pre>
<?php
$cars = [
"Volvo",
"BMW",
"Toyota",
];
var_dump($cars);
?>
</pre>
Result View Example
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:
<h4>Array_Keys</h4>
<pre>
<?php
$cars1 = [
0 => "Volvo",
1 => "BMW",
2 =>"Toyota"
];
var_dump($cars1);
?>
</pre>
<hr>
<p>As you can see, indexed arrays are the same as associative arrays, but associative arrays have names instead of numbers:</p>
<pre>
<?php
$myCar2 = [
"brand" => "Ford",
"model" => "Mustang",
"year" => 1964
];
var_dump($myCar2);
?>
</pre>
Result View Example
You can declare an empty array first, and add items to it later:
<h4>Declare_Empty_Array</h4>
<pre>
<?php
$cars = [];
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
var_dump($cars);
?>
</pre>
<hr>
<p>The same goes for associative arrays, you can declare the array first, and then add items to it:</p>
<pre>
<?php
$myCar = [];
$myCar["brand"] = "Ford";
$myCar["model"] = "Mustang";
$myCar["year"] = 1964;
var_dump($myCar);
?>
</pre>
Result View Example
<h4>Mixing_Array_Keys</h4>
<p>You can have arrays with both indexed and named keys:</p>
<pre>
<?php
$myArr = [];
$myArr[0] = "apples";
$myArr[1] = "bananas";
$myArr["fruit"] = "cherries";
var_dump($myArr);
?>
</pre>
Result View Example
Document in project
You can Download PDF file.