PHP Update Array Items

0
4K

Update Array Item

To update an existing array item, you can refer to the index number for indexed arrays, and the key name for associative arrays.

ExampleGet your own PHP Server

Change the second array item from "BMW" to "Ford":

$cars = array("Volvo", "BMW", "Toyota");
$cars[1] = "Ford";
Try it Yourself »

Note: The first item has index 0.

To update items from an associative array, use the key name:

Example

Update the year to 2024:

$cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964);
$cars["year"] = 2024;
Try it Yourself »

Update Array Items in a Foreach Loop

There are different techniques to use when changing item values in a foreach loop.

One way is to insert the & character in the assignment to assign the item value by reference, and thereby making sure that any changes done with the array item inside the loop will be done to the original array:

Example

Change ALL item values to "Ford":

$cars = array("Volvo", "BMW", "Toyota");
foreach ($cars as &$x) {
  $x = "Ford";
}
unset($x);
var_dump($cars);
Try it Yourself »

Note: Remember to add the unset() function after the loop.

Without the unset($x) function, the $x variable will remain as a reference to the last array item.

To demonstrate this, see what happens when we change the value of $x after the foreach loop:

Example

Demonstrate the consequence of forgetting the unset() function:

$cars = array("Volvo", "BMW", "Toyota");
foreach ($cars as &$x) {
  $x = "Ford";
}

$x = "ice cream";

var_dump($cars);
Try it Yourself »
Search
Categories
Read More
Other
PHP $GLOBALS
$GLOBALS is an array that contains all global variables. Global Variables Global...
By PHP Tutorial 2024-05-17 08:08:27 0 4K
Other
PHP Constants
Constants are like variables, except that once they are defined they cannot be changed or...
By PHP Tutorial 2024-05-17 07:39:53 0 4K
Other
تطورات التعلم الآلي وتأثيرها على مستقبل العمل
مقدمة: في ظل التطورات السريعة للتكنولوجيا والابتكار، أصبح التعلم الآلي...
By MOHAMED ATTALLAH 2024-05-14 13:56:58 0 4K
Other
PHP Access Arrays
Access Array Item To access an array item, you can refer to the index number for indexed arrays,...
By PHP Tutorial 2024-05-17 08:02:32 0 5K
Other
PHP Magic Constants
PHP Predefined Constants PHP has nine predefined constants that change value depending on where...
By PHP Tutorial 2024-05-17 07:40:16 0 2K