Many times you need to replace a value in an array or object, and iterating through the elements is not always so simple.
But are you sure you need to iterate through the elements?
Imagine you have this array:
$arr = array( 'el1' => 1,'el2' => array( 'testing1','testing2' );
Or this object:
$obj = new stdClass; $obj->el1 = 1; $obj->el2 = array( 'testing1','testing2' );
And you want to replace ‘testing’ with ‘replaced’.
In this case, the array and the object are very simple, and it will not be difficult to iterate through the elements. In more complex situations, the solution is still very simple, and I wonder why many developers don’t do it. I’ve seen crazy methods to simply replace a value with another one. In the code of many plugins and blog posts, I see very complex foreach cycles, but the solution would be one line of code 🙂 And it works.
Please, use your time for more complex problems, and save the keys of your keyboard, if you need to replace an element in an array or object, you only need a function with one line of code:
function jose_replace_in_array_or_object( $search,$replace,$array_or_object ){ return $array_or_object ? json_decode( str_replace( $search,$replace,json_encode( $array_or_object ) ),is_array( $array_or_object ) ) : $array_or_object; }
In the example:
$arr2 = jose_replace_in_array_or_object( 'testing','replaced',$arr );
$arr2 will output:
Array ( [el1] => 1 [el2] => Array ( [0] => replaced1 [1] => replaced2 ) )
In the case of the object
$obj2 = jose_replace_in_array_or_object( 'testing','replaced',$obj );
$obj2 will output:
stdClass Object ( [el1] => 1 [el2] => Array ( [0] => replaced1 [1] => replaced2 ) )
The trick is very simple. We convert the array or the object to a string with json_encode, we do the replacement, and we convert it again to an array or an object depending on the input. One line of code. That’s it.
Applications
Of course, you can’t always use this method. You have to be sure that the replacement doesn’t have any effect on the keys, and be sure that you don’t match values that should not be changed.
You can use it to replace for instance URLs with other URLs, or strings that will never be used for the keys. Most of the time you can use it, but be careful.