Reputation: 3209
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
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
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.
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
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
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