ternary condition or if and else with PHP

2

I would like to know, when I should use these types of conditions, I already did the test returns the same thing to me, but what's the difference? I believe it is not only diminish lines, but we will 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 is the second 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?

    
asked by anonymous 20.12.2017 / 15:37

1 answer

3

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 since it is not possible to have 'N lines' in the ternary.

You can optimize your example so that you are testing a condition and the return of an expression is always Boolean so its return will be true or false .

return $count->rowCount() > 0

The translation of the execution would look something like:

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

1 - Execute and return method rowCount()

2 - Tests the expression for example: 3 > 0

3 - Find the response (Boolean) for the expression of item 2, return in steps this value as method return / function.

Recommended reading:

What's the difference between a statement and an expression?

    
20.12.2017 / 15:43