Table of Contents
To add items to an existing array, you can use the bracket [] syntax.
<h4>Add_Array_Item</h4>
<p>Add one more item to the fruits array:</p>
<pre>
<?php
$fruits = array("Apple", "Banana", "Cherry");
$fruits[] = "Orange";
//Output the array:
var_dump($fruits);
?>
</pre>
Result View Example
To add items to an associative array, or key/value array, use brackets [] for the key, and assign value with the = operator.
<h4>Associative_Arrays</h4>
<p>Add one item to the car array:</p>
<pre>
<?php
$cars = array("brand" => "Ford", "model" => "Mustang");
$cars["color"] = "Red";
//Output the array:
var_dump($cars);
?>
</pre>
Result View Example
To add multiple items to an existing array, use the array_push() function.
<pre>
<?php
$fruits = array("Apple", "Banana", "Cherry");
array_push($fruits, "Orange", "Kiwi", "Lemon");
//Output the array:
var_dump($fruits);
?>
</pre>
Result View Example
To add multiple items to an existing array, you can use the += operator.
<h4>Add_Multiple_Items_to_Associative_Arrays</h4>
<p>To add multiple items to an existing array, you can use the += operator.</p>
<pre>
<?php
$cars = array("brand" => "Ford", "model" => "Mustang");
$cars += ["color" => "red", "year" => 1964];
//Output the array:
var_dump($cars);
?>
</pre>
Result View Example
Document in project
You can Download PDF file.