PHP Update Array Items

0
7KB

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 »
Suche
Kategorien
Mehr lesen
Andere
PHP Strings
A string is a sequence of characters, like "Hello world!". Strings Strings in PHP are...
Von PHP Tutorial 2024-05-17 07:28:17 0 6KB
Andere
PHP Math
PHP has a set of math functions that allows you to perform mathematical tasks on numbers. PHP...
Von PHP Tutorial 2024-05-17 07:39:09 0 6KB
Andere
PHP Sorting Arrays
The elements in an array can be sorted in alphabetical or numerical order, descending or...
Von PHP Tutorial 2024-05-17 08:06:46 0 8KB
Andere
PHP Casting
Sometimes you need to change a variable from one data type into another, and sometimes you want a...
Von PHP Tutorial 2024-05-17 07:38:02 0 4KB
Andere
PHP while Loop
The while loop - Loops through a block of code as long as the specified condition is...
Von PHP Tutorial 2024-05-17 07:48:58 0 4KB
Sociallez https://sociallez.com