ternary or if and Else condition with PHP

Asked

Viewed 266 times

2

I would like to know, when I should use these kinds of conditions, I have already made the test returns me the same thing, but what is the difference? I believe it is not only decrease lines, but let’s combine the second option is cleaner right?

public function method($param) {
    $sql = "SELECT * FROM `table` WHERE field = :field";

    $count = $this->_db->select($sql, array('method' => $param[1]));

    if ($count->rowCount() > 0) {
        return true;
    } else {
        return false;
    }
}

Here’s the second one with ternary condition.

public function method($param) {
    $sql = "SELECT * FROM `table` WHERE field = :field";

    $count = $this->_db->select($sql, array('method' => $param[1]));

    return $count->rowCount() > 0 ? true : false;
}

What promotes difference in my code?

  • You don’t even need the ternary, you can just come back: return $count->rowCount() > 0.

  • @rray is that I will use in another function, in a vip system, if vip returns true if not false, true executes a query, and false executes another.

  • 1

    I think what he meant was, by just putting return $count->rowCount() > 0 will already return true or false

1 answer

2


In this example it is the same thing. Whenever performing a single action the ternary is a good candidate in place of the if/Else. If you have more instructions to execute you will need the traditional conditional as it is not possible to have 'N lines' in the ternary.

You can optimize your example like this, because you are testing a condition and the return of an expression is always boolean soon your return will be true or false.

return $count->rowCount() > 0

The translation of the execution would be something like:

return $count->rowCount() > 0
^            ^            ^
3            1            2

1 - Executes and obtains the return of the method rowCount()

2 - Test the expression for example: 3 > 0

3 - Discovery the answer (boolean) to the expression of item 2, the return in walk this value as return of the method/function.

Recommended reading:

What is the difference between a statement and an expression?

  • is worked msm way so do not need to do Return $count->rowCount() > 0 ? true : false; what simple no? kkkk

Browser other questions tagged

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