Replace all `null` values in an array in PHP
May 5, 2022 ‐ 1 min read
To replace all occurrences of
null in an array with another value you can use the
array_map() function that is built into PHP. This function applies a callback function to each item in your array and returns a new array with all the return values of that callback function.
As a first argument
array_map() takes the callback function, as a second argument it takes an array of values on which the callback function should be applied.
To replace all
null values by another value, the letter "c" in this example, you can take the following snippet:
<?php $REPLACEMENT = 'c'; $values = ['a', 'b', null, 'd']; $result = array_map( fn ($value) => $value ?? $REPLACEMENT, $values ); print_r($result); // Array // ( //  => a //  => b //  => c //  => d // )
Keep in mind here that in the above snippet I'm using two features that are at the time still fairly recent: the null coalescing operator and an arrow function.
The null coalescing operator returns the first operand, except for when it is
null in which case it falls back to the second operand.
PHP arrow functions were introduced in PHP 7.4 and provide a more comprehensive syntax to closures, also known as anonymous functions.