1

I want to test if an object is null or not, I have the follwing code

$listcontact = array();
$contact=$ms->search('email','test@live.Fr');
var_dump(($contact));

and the result if $listcontact not null is give as follow

object(stdClass)[6]
public 'item' => string 'dfdfsd' (length=7)

in the case it's null , I get the following result

object(stdClass)[6]

How I can test the variable $listcontact exists or not? I've tried with is_null and (empty() but not work

Praveen Kumar Purushothaman
  • 160,666
  • 24
  • 190
  • 242
Majdi Taleb
  • 683
  • 2
  • 9
  • 24
  • You can use `count` method of php [Documentation Link](http://php.net/manual/en/function.count.php) – Aatman Jan 28 '16 at 12:01
  • How is *$listcontact* involved in setting *$contact*? Your code does not show any connection. – trincot Jan 28 '16 at 12:04
  • 1
    Possible duplicate of [How to tell if a PHP array is empty?](http://stackoverflow.com/questions/2216052/how-to-tell-if-a-php-array-is-empty) – trincot Jan 28 '16 at 12:15

4 Answers4

5

You can use a built-in function is_null() to check null values. So, use:

if (is_null($listcontact))
  // Yes, it is null.
else
  // Do something.
Praveen Kumar Purushothaman
  • 160,666
  • 24
  • 190
  • 242
4

Use the function is_null() as follows :

is_null($listcontact);

The Return Value is :

Returns TRUE if var is null, FALSE otherwise.

EDIT

Also you can use this :

  if ( !$YOUR_OBJECT->count() ){
        //null
  }

For more information see those answers

Try using array_filter()

$EmptyArray= array_filter($listcontact);

if (!empty($EmptyArray)){

}
else{
    //nothing there
}
Community
  • 1
  • 1
Skizo-ozᴉʞS
  • 18,460
  • 17
  • 76
  • 134
2

If you get object stdclass with var_dump, it must not be null.

The fastest way to check if a variable is null is to use $listcontact === null.

in the case it's null , I get the following result

object(stdClass)[6]

This means that the search() function didn't return null.

SOFe
  • 7,450
  • 4
  • 30
  • 59
0

I found a correct answer for this

 $tmp = (array) $listcontact;
 var_dump(empty($tmp));
if(empty($tmp)){
echo "empty"
}
Majdi Taleb
  • 683
  • 2
  • 9
  • 24