Doubt with ternary operator

0

I have doubts how to interpret this:

    $page = (isset($_REQUEST['page']) && !empty($_REQUEST['page']))?$_REQUEST['page']:1;

Do you mean that if page is not declared and it is not empty, it will pick up the page value and otherwise $ page will take the value "1"?

    
asked by RicardoKra 06.11.2018 в 13:23
source

1 answer

7

A ternary operator is a condition that returns a result.

The condition is written first, before the interrogation, and the result returned behind it. If the condition is met, a value returns, which is the one to the left of the two points, if it is not met, it returns the value on the right.

It would be something like this:

$valor = condición ? $seCumple : $noSeCumple;

In your case it means that if it exists and it is not empty $_REQUEST['page'] its value is returned, if it does not exist it returns 1

In php 7 this function was improved with the ternary operator null (??) which helps to avoid using isset by returning the first non-null value. your example would pass this:

$page = (isset($_REQUEST['page']) && !empty($_REQUEST['page']))?$_REQUEST['page']:1;

to this:

$page = $_REQUEST['page'] ?? 1;
    
answered by 06.11.2018 в 13:57