Guerra
Guerra

Reputation: 2790

Strange PHP behavior: empty, !, and count

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.

Upvotes: 5

Views: 178

Answers (3)

dave
dave

Reputation: 64657

!0 = true;
empty(0) = true;
count(0) = 1

Your value is 0 or an empty string.

Upvotes: -1

Manoj Purohit
Manoj Purohit

Reputation: 3453

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

Upvotes: 6

Matt Dodge
Matt Dodge

Reputation: 11142

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)

Upvotes: 8

Related Questions