0

I'm calling a function to insert some thing in SQL, and I wanted to know if is it safe to have the function as second condition to an if statement, and if it would be called only when the first condition is true, and I would like to know if it would be good pratice too;

I know I could include another if inside that if, and it would work fine, but I'm trying not to include too many unnecessary if statements. It isn't the same as wanting to know if it's better to use nested IFs, because what I wanted to know was if the function would be called when the first condition evaluated to false or not.

if (empty($err) && InsertSQL($args)) {
 echo "success";
} else {
 $err .= "fail to insert";
}

echo $err;

I expect it to output success if there is no error in $err and the function returns true, and "fail to insert" and the other error if there is an error or if there is no error but the function returns false, I'll just get "fail to insert"

Miguel Vieira
  • 144
  • 3
  • 17
  • 1
    Yes, however you just get `fail` and don't know or state why it failed of the 2 conditions. – AbraCadaver May 17 '19 at 19:53
  • @AbraCadaver: I know, but I have code somewhere else that outputs me the errors. I changed the code in the question a bit to show it better, If I got an error before the IF statement, I get both errors, if only the insert failed, I get the insert error – Miguel Vieira May 17 '19 at 19:58
  • Possible duplicate of [What is better ? Multiple if statements, or one if with multiple conditions](https://stackoverflow.com/questions/5259938/what-is-better-multiple-if-statements-or-one-if-with-multiple-conditions) – miken32 May 17 '19 at 20:33
  • 1
    Just bear in mind that if you have an expression such as `true && func()`, `func()` is called whatever its return. – Progrock May 17 '19 at 20:35
  • @Progrock Thanks! That's what I intended: If the function returns true, SQL will be inserted, but if it fails it returns false and I don't get a success message, but an error message telling me it had failed. – Miguel Vieira May 17 '19 at 20:45

1 Answers1

2

Yes, the && short-circuits. So, if the first condition fails it doesn't bother evaluating the second condition. So, the InsertSQL() function would not be called.

MER
  • 328
  • 2
  • 9