If you’re explicitly trying to handle the case of null
, then a slightly cleaner fix would be strlen($row ?? '')
using the “null coalescing operator”.
In most cases, the two are probably equivalent but with strict_types=1
in effect, they behave differently if the value is some other type that can be cast to string:
declare(strict_types=1);
$row = 42;
echo strlen($row); // TypeError: must be of type string, int given
echo strlen((string) $row); // Succeeds, outputting '2'
echo strlen($row ?? ''); // TypeError: must be of type string, int given
On the other hand, note that the ??
operator is based on isset
, not === null
, so an undefined variable will behave differently:
declare(strict_types=1);
$row = [];
echo strlen($row['no_such_key']); // Warning: Undefined array key; TypeError: must be of type string, null given
echo strlen((string) $row['no_such_key']); // Warning: Undefined array key; outputs '0'
echo strlen($row['no_such_key'] ?? ''); // No warning, just outputs '0'
If you care about that case, the most directly equivalent code to the old behaviour is rather more verbose:
echo strlen($row === null ? '' : $row);