user1269625
user1269625

Reputation: 3209

PHP if array is empty

I have an array and when I print the output like so print_r($userExists);

it returns Array ( ) I wrote this code to tell me if the array is empty or not:

if(isset($userExists)){
        echo 'exists';
    }else{
        echo 'does not exists';
    }

But regardless if the array is empty or not, it only returns exists What Am i doing wrong, when the array is populated, it looks like this Array ( [0] => Array ( [id] => 10 ) )

Upvotes: 1

Views: 361

Answers (4)

GrimR1P
GrimR1P

Reputation: 162

You do not need an extra check for if!

if($array){
// Will execute only if there is any value inside of the array
}

By using if there is no need checking if any value is available! you are using 'isset' for variables that might not exist like $_GET value or $_SESSION etc.... 'empty' to check a string value

by php documentation empty works only in string and not arrays

Upvotes: 0

DonCallisto
DonCallisto

Reputation: 29912

Use

if( !empty( $userExists ) ) {
    echo 'exists';
}
else {
    echo 'does not exists';
}

or

if( count( $userExists ) ) {
    echo 'exists';
}
else {
    echo 'does not exists';
}

However is safer to use empty() as if that variable doesn't exists your script will not stop due to exception while count() does.

isset is "not working"* here since this variable is setted (so exists) even if is empty.
So, basically, isset will

Determine if a variable is set and is not NULL.


Last but not least, if you want to know which is "better" for code optimization, I could tell you a little "secret": `count()` doesn't need to traverse the array each time to know how many elements will be there since, internally, it store the elements number (as you can see under), so every call to `count()` function results in `O(1)` complexity.
ZEND_API int zend_hash_num_elements(const HashTable *ht)
{
    IS_CONSISTENT(ht);

    return ht->nNumOfElements;
}

zend_hash_num_elements is called from count() (take a look here)

from php manual



*(not working as you wish/need)

Upvotes: 7

Abhik Chakraborty
Abhik Chakraborty

Reputation: 44844

use as below

if(isset($userExists) && count($userExists) > 0 ){
        echo 'exists';
    }else{
        echo 'does not exists';
    }

OR

You can check if the variable is an array and having some value

if(is_array($userExists) && count($userExists) > 0 ){
    echo 'exists';
}else{
    echo 'does not exists';
}

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

$userExists = array();

The variable exists, and it is set. That's what isset tests for.

What you want is:

if( $userExists) echo "exists";

Upvotes: 0

Related Questions