Skip to main content

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":

Prompt
Write a PHP script that creates an indexed array with "Volvo", "BMW", and "Toyota", then changes the second item to "Ford".
Output: PHP script

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:

Prompt
Write a PHP script that creates an associative array for a car with brand "Ford", model "Mustang", and year 1964, then changes the year to 2024.
Output: PHP script

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":

Prompt
Write a PHP script that creates an indexed array with "Volvo", "BMW", and "Toyota", uses a foreach loop with a reference variable to change all values to "Ford", then calls unset on the reference and displays the array with var_dump().
Output: PHP script

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:

Prompt
Write a PHP script that creates an indexed array with "Volvo", "BMW", and "Toyota", uses a foreach loop with a reference variable to change all values to "Ford", but does NOT call unset, then assigns "ice cream" to the loop variable and displays the array with var_dump().
Output: PHP script