PHP Update Array Items

To update items in a PHP array, you'll typically access the array element by its key or index and assign it a new value. Here's a quick overview with examples:


1. Updating Associative Arrays

$user = [ 'name' => 'Alice', 'age' => 25 ]; // Update the name $user['name'] = 'Bob'; print_r($user);

Output:

Array ( [name] => Bob [age] => 25 )

2. Updating Indexed Arrays

$colors = ['red', 'green', 'blue']; // Update the second color $colors[1] = 'yellow'; print_r($colors);

Output:

Array ( [0] => red [1] => yellow [2] => blue )

3. Updating Array Items with a Loop

You can also update items based on a condition:

$numbers = [1, 2, 3, 4, 5]; // Double each value foreach ($numbers as $index => $value) { $numbers[$index] = $value * 2; } print_r($numbers);

Output:

Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 )