Updating Array Items

Updating items in arrays is super simple — you just target either the index (for numbered arrays) or the key (for associative arrays).

Updating an indexed array

Example: change "BMW" to "Ford":

$cars = ["Volvo", "BMW", "Toyota"];
$cars[1] = "Ford"; // index 1 = second item

Indexes start at 0, always.


Updating an associative array

You use the key name:

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

Updating items inside a foreach loop

If you want to modify the original array, not a copy, you must use & (reference):

$cars = ["Volvo", "BMW", "Toyota"];

foreach ($cars as &$x) {
  $x = "Ford";     // modifies the original array
}

unset($x); // VERY IMPORTANT

If you forget unset($x), PHP keeps $x pointing to the last array item in memory.

So if you later do:

$x = "ice cream";

…it will overwrite the last element of $cars.


That’s why unset($x) is mandatory after a reference-based foreach.