HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

PHP Update Array Items

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


Example

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


<!DOCTYPE html>
<html>
<body>
<pre>

<?php  
$cars = array("Volvo", "BMW", "Toyota");
$cars[1] = "Ford";
var_dump($cars);
?>  

</pre>
</body>
</html>


Output

array(3) {
[0]=>
string(5) "Volvo"
[1]=>
string(4) "Ford"
[2]=>
string(6) "Toyota"
}

• Update Array Items in a Foreach Loop

The foreach loop is a common construct in PHP used to iterate over arrays. It allows you to access and potentially modify each element's value during the iteration.

Assignment by Reference: In PHP, you can create assignments that modify the original value in a variable instead of creating a copy. This is called assignment by reference.

Using the & Operator: The & symbol is used before a variable in an assignment to indicate that you want to assign by reference.

Modifying Array Items: This concept can be applied to array elements within loops to make changes that directly affect the original array.




Example

Change ALL item values to "Ford":

<!DOCTYPE html>
<html>
<body>
<pre>

<?php  
$cars = array("Volvo", "BMW", "Toyota");
foreach ($cars as &$x) {
  $x = "Ford";
}
unset($x);
var_dump($cars);
?>  

</pre>
</body>
</html>

Output

array(3) {
[0]=>
string(4) "Ford"
[1]=>
string(4) "Ford"
[2]=>
string(4) "Ford"
}