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

Update Array Items

Update Array Item

To update an existing array item, use the index number for indexed arrays or the key name for associative arrays.

Example

Replace the second array item “BMW” with “Ford”:

$cars = array("Volvo", "BMW", "Toyota");
$cars[1] = "Ford";
Note: The first item is at index 0.

To update items in an associative array, use the key name.

Example

Change the year to 2024.

$cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964);
$cars["year"] = 2024;

Update Array Items in a Foreach Loop

There are various techniques for changing item values in a foreach loop.

One approach is to use the & character in the assignment to assign the item value by reference. This ensures that any modifications made to the array item inside the loop will affect the original array.

Example

Replace ALL item values with “Ford”.

$cars = array("Volvo", "BMW", "Toyota");
foreach ($cars as &$x) {
 $x = "Ford";
}
unset($x);
var_dump($cars);

Note: Remember to include the unset() function after the loop.

Without unset($x), the $x variable will remain a reference to the last array item.

To illustrate this, observe what happens when we change the value of $x after the foreach loop:

Example

Show the consequence of forgetting the unset() function:

$cars = array("Volvo", "BMW", "Toyota");
foreach ($cars as &$x) {
 $x = "Ford";
}
$x = "ice cream";
var_dump($cars);