PHP Update Array Items

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

Example
<!DOCTYPE html>
<html>
<body>
<?php
$fruits = ["Apple", "Banana", "Cherry"];
$fruits[1] = "Blueberry"; // Changes the element at index 1 to "Blueberry"
var_dump($fruits);
?>
</body>
</html>

Try it yourself

Updating Items in an Associative Array


To update a value in an associative array, use the key of the element you want to modify.

Example
<!DOCTYPE html>
<html>
<body>
<?php
$person = array(
"name" => "Alice",
"age" => 30,
"city" => "New York"
);
$person["age"] = 31; // Updates the value of "age" to 31

var_dump($person);
?>
</body>
</html>

Try it yourself

Using Loops to Update Array Elements


You can use the foreach loop to iterate over an indexed array and modify each element.


The ampersand (&) creates a reference, allowing you to modify the original array elements.

Example
<!DOCTYPE html>
<html>
<body>
<?php
$numbers = [1, 2, 3, 4, 5];

foreach ($numbers as &$value) {
$value *= 2; // Multiply each element by 2
}

unset($value); // Unset reference to avoid unexpected behavior

print_r($numbers);
// Output: [2, 4, 6, 8, 10]
?>
</body>
</html>

Try it yourself

Note

It's important to unset() the reference after the loop.

If you don't unset() it afterward, the reference can still point to the last item in the array even outside the loop.

Demonstrate the consequence of forgetting the unset() function:

Example
<!DOCTYPE html>
<html>
<body>
<?php
$numbers = [1, 2, 3, 4, 5];

foreach ($numbers as &$value) {
$value *= 2;
}
// No `unset($value);` here

$value = 100; // Accidentally modifies the last element

print_r($numbers);
// Output: [2, 4, 6, 8, 100]

?>
</body>
</html>

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.