Home > database >  is_null function is not working in object values
is_null function is not working in object values

Time:03-09

I would like to loop through an object like this

 0 => 
object(stdClass)[13]
  public 'first_name' => string 'toto' (length=7)
  public 'last_name' => string 'titi' (length=7)
  public 'phone_1' => null
1 => 
object(stdClass)[14]
  public 'first_name' => string 'tutu' (length=7)
  public 'last_name' => string 'tata' (length=8)
  public 'phone_1' => string '123' (length=9)

This object come from a PDO::FetchAll(PDO::fetchobject).

My foreach loop:

foreach($users as $user){
    echo (!is_null($user->phone)) ? $user->phone : '';
}

But I got this error message: trying to get property 'phone_1' of non-object in

May someone help me for this ?

Thank you

CodePudding user response:

I found how to do :

 <?php echo isset($user->phone) ? $user->phone : ''; ?> 

CodePudding user response:

This:

echo (!is_null($user->phone)) ? $user->phone : '';

... can be simplified to:

echo $user->phone;

If the property is null, it'll cast automatically to empty string ('').

If you get trying to get property 'phone' of non-object1 it's because you don't have an object to begin with. That's a different problem.

If you're looping the results of a database query, you shouldn't need to check for object existence, and doing so might mask a bug in some other part of your code. A possible cause is that your query is failing and fetchAll() returns false.

1 Please note I've fixed the property name in the error message, assuming it was a copy paste error. If you really read phone and get an error about phone_1, you didn't check the correct line.

  • Related