SimonHRD's avatar

Call to a member function count() on null

Hi all

I have some problems to call the function count() on null variables. I do someting like this:

...

if(some condition)
{
	$var = null;
}

...

$var->count();

How I can do this without getting this null error? If the $var is null then the count() function should just return 0.

Thank you!

0 likes
1 reply
tykus's avatar
tykus
Best Answer
Level 104

Null-safe operator (PHP > 8.0)

$var?->count() ?? 0;

or

$var ? $var->count() : 0;
1 like

Please or to participate in this conversation.