PHP Update Array Items
Changing an item starts with finding it, using the index number in an indexed array or the key name in an associative array.
Example
Replace "BMW", the second item, with "Ford":
Output: PHP script
<?php
$cars = array("Volvo", "BMW", "Toyota");
$cars[1] = "Ford";
?>
Update Associative Array Item
Note: Remember that indexing begins at 0, which is why the second item is $cars[1].
Associative arrays follow the same pattern with the key name:
Example
Set the year item to 2024:
Output: PHP script
<?php
$cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964);
$cars["year"] = 2024;
?>
Update Array Items in a Foreach Loop
You have more than one option for changing values inside a foreach loop.
One of them is to put the & character before the loop variable. The variable then holds a reference to each item rather than a copy, so whatever you do to it inside the loop also changes the original array:
Example
Set every item to "Ford":
Output: PHP script
<?php
$cars = array("Volvo", "BMW", "Toyota");
foreach ($cars as &$x) {
$x = "Ford";
}
unset($x);
var_dump($cars);
?>
Forgetting unset()
Note: Always call unset() once the loop ends. Without it, $x stays linked to the last item of the array.
The next example leaves out that call and then assigns a new value to $x after the loop. Look at what happens to the last item:
Example
With no unset(), the new value of $x overwrites the last car:
Output: PHP script
<?php
$cars = array("Volvo", "BMW", "Toyota");
foreach ($cars as &$x) {
$x = "Ford";
}
$x = "ice cream";
var_dump($cars);
?>