Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange PHP behavior: empty, !, and count

Tags:

php

Someone can explain to me if this "freak" behavior its what i should expect.

I'm debbuging some code and got this:

I geting some result on $data and create this if to be sure it's $data have some info.

So:

if(!$data || empty($data) || count($data) == 0)

And aways geting in the if.

So i do some var_dump to see and wow.

var_dump(!$data , empty($data) , count($data));

go this:

bool(true)
bool(true)
int(1)

how count data = 1 and !$data = true and empty($data) = true?

I hope isn't stupid question, i'm sorry if is.

like image 861
Guerra Avatar asked May 02 '13 20:05

Guerra


2 Answers

From the PHP Documentation on count.

Returns the number of elements in var. If var is not an array or an object with implemented Countable interface, 1 will be returned. There is one exception, if var is NULL, 0 will be returned.

Most likely, $data is not an array. Double check with a var_dump on it

var_dump($data)
like image 157
Matt Dodge Avatar answered Nov 15 '22 01:11

Matt Dodge


Count Returns the number of elements in var. If var is not an array or an object with implemented Countable interface, 1 will be returned. There is one exception, if var is NULL, 0 will be returned.

Look at PHP Documentation http://php.net/manual/en/function.count.php

like image 28
Manoj Purohit Avatar answered Nov 15 '22 00:11

Manoj Purohit