Multi Dimensional Array in PHP | Associative Array in PHP
When a user wants to replace current values of arrays with other values, then two functions of PHP arrays are used. These arrays do not replace new values in an existing array. They will create a new array and then store these values in the new array. They are:
- Array_replace
- Array_replace_recursive
Array_replace() arrays are used with index or associative arrays.
Array_replace_recursive() arrays are used with Multidimensional associative array.
array_replace()
In case of indexed array with 2 variables
<?php $food = ["apple", "orange", "mango"]; $veggie = ["carrot", "capsicum"]; $newarray = array_replace($food, $veggie); echo "<pre>"; print_r($newarray); echo "</pre"; ?>
Output:
Array ( [0] => carrot [1] => capsicum [2] => mango )
Explanation: apple and orange will be replaced by carrot and capsicum.
In case of indexed array with 3 variables:
<?php $food = ["apple", "orange", "mango", "banana"]; $veggie = ["carrot", "capsicum"]; $color = ["red"]; $newarray = array_replace($food, $veggie, $col); echo "<pre>"; print_r($newarray); echo "</pre"; ?>
Output:
Array ( [0] => red [1] => capsicum [2] => mango [3] => banana )
In case of associative arrays
<?php $food = ["apple", "orange", "mango", "banana"]; $veggie = ["a" => "carrot", "b" => "capsicum"]; $newarray = array_replace($food, $veggie); echo "<pre>"; print_r($newarray); echo "</pre"; ?>
Output:
Array ( [0] => apple [1] => orange [2] => mango [3] => banana [a] => carrot [b] => capsicum )
In case of associative arrays with index number:
<?php $food = ["apple", "orange", "mango", "banana"]; $veggie = ["a" => "carrot", 1 => "capsicum"]; $newarray = array_replace($food, $veggie); echo "<pre>"; print_r($newarray); echo "</pre"; ?>
Output:
Array ( [0] => apple [1] => capsicum [2] => mango [3] => banana [a] => carrot )
When we define index number in an array, that means we are telling the function to replace the value of orange at 1 index number of $food with new value capsicum.
Example 2:
<?php $food = ["apple", "orange", "a" => "mango", "banana"]; $veggie = ["a" => "carrot", 1 => "capsicum"]; $newarray = array_replace($food, $veggie); echo "<pre>"; print_r($newarray); echo "</pre"; ?>
Output:
Array ( [0] => apple [1] => capsicum [a] => carrot [2] => banana )
array_replace_recursive
<?php $food = ["a" => ["apple"], "b" => ["orange", "pink"]]; $veggie = ["a" => ["red"], "b" => ["yellow"]]; $newarray = array_replace_recursive($food, $veggie); echo "<pre>"; print_r($newarray); echo "</pre"; ?>
Output:
Array (
[a] => Array (
[0] => red
)
[b] => Array (
[0] => yellow
[1] => pink
)
)
