Isset in PHP ternary?

Asked

Viewed 264 times

1

I have the following examples of condition in ternario, in the first example it works correctly, it returns me the data and if it is empty returns null, however in the second example I think would be correct, it returns me the data correctly but does not return me null when empty.

Example 1:

$data->mala_grande = ($t->malagrande) ? $t->malagrande :null;  

Example 2

$data->mala_grande = (isset($t->malagrande)) ? $t->malagrande :null;
  • Would you be doing something wrong using this first example without the isset?
  • I can continue on this option?
  • The first option Without putting the isset she would be playing the same role automatically?
  • 4

    isset() not to test if it’s empty. empty() is to test if it’s empty.

  • o the problem is that with Empty() the same thing occurs

  • I complemented the answer and put another example. I hope you answer.

1 answer

4


isset() is not used to test if a value is empty. The function is to check whether the variable is set or not.

The empty() is to test whether a variable is "empty", and has the same property as the isset of not generating a Warning if the variable is missing:

$data->mala_grande = ! empty($t->malagrande) ? $t->malagrande : null;
//                   ^ o ! inverte a lógica do teste                      

Or else

$data->mala_grande = empty($t->malagrande) ? null : $t->malagrande;

In the first case we are using the not Empty (! empty()), that is to say:

  • "if nay for empty returns t->malagrande, otherwise null.

In the second case:

  • "if empty returns null, otherwise, t->malagrande.

They result in the same thing, written in different ways.

Handbook:

https://www.php.net/manual/en/function.empty.php

  • o the problem is that with Empty occurs the same thing

  • 1

    @Fabiohenrique without the Empty, if $t for null, is not an object, or is an object but does not have that property malagrande, will give an error. Checking with empty prevents this. That would be the question?

  • More Me asks a question because in the first example it works correctly, when I do not put neither Insert nor Empty

  • 2

    It does not work properly, it generates a Warning. What can happen is you are not looking at the error log so it is apparently ok (but Warning happens and goes to a log file if everything is configured correctly).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.