norr norr - 1 year ago 89
PHP Question

Handle false return from function. IF vs OR vs Ternary operators etc

What's the "best" way to handle FALSE return from function, to call another function? For example I have "$stmt->execute();" from PDO and want to know when query execute failed.


function test() {
return false;

function error($err) {
echo $err;

if (!test()) error('a'); // method 1
test() OR error('b'); // method 2
test() || error('c'); // method 3
test() ?: error('d'); // method 4

This will show "abcd". If I change test() return to true then nothing will show up so all 4 methods works. But what is the "best"? If all methods are the same "correct" in programming way, then what is more often used, nicer, modern, maybe more correct for coding standards like PSR? Maybe there is even another better method?

Answer Source

In this very simple instance, I think it's really a matter of choice. Because you have just one statement to execute if the test fails, and nothing to do if it passes, everything easily fits on one line. Anything but the last line is easy to read and probably fine.

In most cases though, the result of the true/false test will lead to more than just one statement. This binary branching is the whole purpose of the if-else construct, so I tend to use that.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download