search and replace value in PHP array

In PHP, you can use the array_map() function to search and replace values in an array. Here's an example:

<?php

$originalArray = [1, 2, 3, 4, 5];
$newArray = array_map(function ($value) {
    return $value == 3 ? 9 : $value;
}, $originalArray);
print_r($newArray);

In this example, the array_map() function is used to iterate through each element of the $originalArray and apply the anonymous function to each element. The anonymous function checks if the current value is equal to 3, and if so, replaces it with 9. The modified array is then stored in $newArray.

Watch a course Learn object oriented PHP

If you want to replace all the values that match some condition with a specific value, you can use the array_map() function.

<?php

$originalArray = [1, 2, 3, 4, 5, 6, 7];
$newArray = array_map(function ($value) {
    if ($value % 2 == 0) {
        return 0;
    } else {
        return $value;
    }
}, $originalArray);
print_r($newArray);

In this example, the function checks if the current value is an even number, and if so, replaces it with 0. The modified array is then stored in $newArray.