PHP ternary operators

150 views Asked by At

I have written a ternary function in PHP and it seems to work, although I am not sure if it is correct, can someone take a look and tell me if it is right?

I have added the ternary and the if of what should be happening.

    //Foreach Loop
    foreach ($post as $item) {
        //If of what should occur
        if ($passed == true) {
            if (is_numeric($item)) {
                if ($item > 0) {
                    $passed = true;
                }
                else {
                    $passed = false;
                }
            }
            else {
                if ($item != "") {
                    $passed = true;
                }
                else {
                    $passed = false;
                }
            }
            //Ternary operator.
            $passed = (is_numeric($item) ? ($item > 0 ? true : false) : ($item != "" ? true : false));
        }
        else {
            return $passed;
        }
    }
2

There are 2 answers

0
kevin On BEST ANSWER

please have a look on corrected code

$passed = (is_numeric($item))?($item>0?true:false):($item !="" ? true:false);

1
PEM On

Honestly I do not really understand why you do not use a

if (!empty($item)) { 
    $passed = true; 
} else {
    return false; 
} 

In any case, ternaries are less readable than if /elseif / else, they are also slower (note that it is not an universal truth but a more general use case thing http://fabien.potencier.org/the-php-ternary-operator-fast-or-not.html). I would recommend, if you really need all these if and elses to keep them rather than using ternaries (for readability's purpose).