PHP Add Array Items

Back to ACP page

Table of Contents

PHP 1 Add Array Item

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>

Example 1

Result View Example

PHP 2 Associative Arrays

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>

Example 2

Result View Example

PHP 3 Add Multiple Array Items

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>

Example 3

Result View Example

PHP 4 Add Multiple Items to Associative Arrays

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>

Example 4

Result View Example

Document

Document in project

You can Download PDF file.

Reference