Passing null to non-nullable internal function parameters – Updating Existing Code Base to php 8.1

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:

$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:

$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);

Leave a Comment