Skip to Content
Learn
Associative Arrays
Changing and Removing Elements

The same syntax that adds new array elements can be used to change existing elements:

$new_arr = ["first" => "I am first!", "second" => "I am second!"]; $new_arr["third"] = "I am third!"; echo $new_arr["third"]; // Prints: I am third! $new_arr["third"] = "I am the *NEW* third!"; echo $new_arr["third"]; // Prints: I am the *NEW* third!

In the above code, we use the same syntax to add a key=>value pair ("third" => "I am third!") as we do to assign that key a new value ("third" => "I am the *NEW* third!").

Since PHP will allow us to add a new key=>value pair or change an existing value using exactly the same code, we’ll need to use caution to avoid accidentally overwriting an existing value.

We can remove a key=>value pair entirely using the PHP unset() function. Note: if the key used doesn’t exist in the array, then nothing happens.

$nums = ["one" => 1,"two"=> 2]; echo implode(", ", $nums); // Prints: 1, 2 unset($nums["one"]); echo implode(", ", $nums); // Prints: 2

In the code above, we created an associative array with two key => value pairs. We then removed the pair "one" => 1 using the unset() function.

Let’s practice changing and removing elements!

Instructions

1.

We’ve provided an associative array, $my_car, with key=>value pairs that relate to elements (or parts) of our car. Some things, like our brakes, seem to be in great shape, but others could use some work…

Change the value associated with the key "oil" from its current value ("black and clumpy") to the value "new and premium".

Note: Accomplish this task without changing the code we wrote.

2.

Change the value associated with the key "tires" from its current value ("old with worn treads") to the value "new with deep treads".

Note: Accomplish this task without changing the code we wrote.

3.

We’d love a clean car. Use the unset() function to remove the "filth" from our car please.

4.

At the bottom of your code, use print_r() to print out $my_car so you can see all the changes to made to the array.

Folder Icon

Take this course for free

Already have an account?