PHP Update Array Items

Back to ACP page

Table of Contents

PHP 1 Update Array Item

To update an existing array item, you can refer to the index number for indexed arrays, and the key name for associative arrays.

<h4>Update_Array_Item</h4> <?php $cars = array("Volvo", "BMW", "Toyota"); $cars[1] = "Ford"; var_dump($cars); ?>

Example 1

Result View Example

PHP 2 Update Array use key name

<h4>Update_Array_use_key_name</h4> <p>To update items from an associative array, use the key name:</p> <pre> <?php $cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964); $cars["year"] = 2024; var_dump($cars); ?> </pre>

Example 2

Result View Example

PHP 3 Update Array Items in a Foreach Loop

<h4>Update_Array_Items_in_a_Foreach_Loop</h4> <p>Change ALL item values to "Ford":</p> <?php $cars = array("Volvo", "BMW", "Toyota"); foreach ($cars as &$x) { $x = "Ford"; } unset($x); var_dump($cars); ?>

Example 3

Result View Example

Document

Document in project

You can Download PDF file.

Reference