A simple question that could remove the need for quite a lot of if/else statements.
If, for example, I have such a query:
if ($success1=$db->query('SELECT * FROM `foo`;') || $success2=$db->query('SELECT * FROM `bar`;')) {
...
}
Would it stop checking when the first query is successful or not?
What you're referring to is called a short circuit. Yes php uses short circuits. With AND (&&) If the first check in the conditional fails, it never checks the second. The same applies for OR ( || ). If the first check succeeds it never looks at the second statement.
See the following post for verification:
PHP short circuit lazy evaluation, where is it in the php.net manual?
An example of when this is very useful is when dividing by zero. In the first check you determine if the denominator is zero, and then in the second check you do the dividing. The order is important. If the denominator is zero it will skip the second check and will never divide by zero.
if($x != 0 && 10/$x > 3)
If the first one is true, then it will not need to check anything else in the statement so it will carry on. If not, code like this:
if(isset($var) && $var == 1)
Would never work as it would throw up a not defined error. As soon as it sees the first one is false, it stops the rest of the statement.
Related
This if statement triggers regardless of the values in the condition , i substituted number for explanation sake. Why is the condition triggering the execution regardless if the condition is true or not. Ive tried every scenario but the execution in the statement triggers every time .
if(1 != 1 && 1 != 2 ){
execute code
exit();
}
here is the exact code:
if($name1 != $winner && $name2 != $winner ){
echo " The player you chose as winner is not associated with match id: $match_id ";
exit();
}
It is not possible for the condition mentioned in the post to return true.
However what you are saying may happen if you write code something like below:
if(1 != 1 && 1 != 2 );{
echo 'case 1';
}
Note the ; after the if(). Are you sure your code does not have the semi-colon after the if()? If you have mistakenly placed a ; then the if statement is evaluated as a single line statement and the code within the if-block is considered by the interpreter as outside of the if condition.
Edit based on the updated question
Please check the following:
$winner is correctly set to either of $name1 or $name2.
Verify that variable declaration scope for $winner is correct - it has been some time since I have done PHP but this is possibly something else to look out for.
Other than these I do not see any other reason why this code should behave the way you state.
Just maybe ... Have a very close look at the values of the four variables involved.
Comparisons using != can give some surprising results.
See here and here. EDIT: Links fixed
Even if that doesn't solve this problem, better to try to use !== wherever possible.
I want to try and make my code as efficient as possible and from what ive read
if($process == true)
Will process faster than something that calls a function. I.e
if(count($total) == 100)
So if i had an OR inside my if and the first condition was a simple boolean check and it turned out to be true would the second part of the condition still be checked anyway?
For example
$process = true;
if($process == true || count($total) == 100)
Would the count function still be called even though process is true and that is enough the make the condition pass.
PHP has indeed a mechanic named short-circuit:
http://php.net/manual/en/language.operators.logical.php#example-140
If the first operand of a logical OR is true, then the second part isn't evaluated, and the function isn't called.
Since comparing a variable to a boolean is faster than calling a function in PHP, this mechanic can help you to optimize, but never forget that premature optimisation is the root of all evil.
It will work same as exactly logical operator works. For example foo() will never get called.
if (false && foo()) {
}
if (true || foo()) {
}
In case of OR once it found a true statement it wont check further conditions,
In case of AND once it found a false statement it wont check further conditions.
its known as lazy evaluation.
illustration:
<?php
$var=0;
if($var++ || $var++){//Since 0 means false in Php both conditions will be checked
//Do nothing
}
echo $var;//output :2
if we change condition to if(++$var || $var++) the first condition will return true hence next condition will not be checked thus it will print output as 1;
If any statement inside a or is true other statements will not be checked and the if will be evaluated to true.
If you are checking a and statement all statements needs to evaluate to true and if any of them is false the stamen check will stop because the if is already false.
Just another important detail is that a function inside a if does not slow down the if check, what will slow down is what the function is doing and if it needs a lot of processing of course will be slower than just check a boolean but do not get afraid of use functions because they are very important in any system.
(I remember this from C# but I'm quite sure it's the same in php)
This depends if you use the single | or double || I think if you used the single ones it would still go do the other one ( usefull for when theres a function like loggin behind it ) if you use double and the first one is true it'll skip the second condition.
(This could be the other way around, so best bet is to try it using Javascript eg. create 2 function each returning true after alerting something, and thest these with either 1 line or 2)
i am trying to check whther $_GET['id'] is set and is numeric else killing the code execution.,
following both codes are working for me , but would like to know whats the difference in between them ?
php condition 1
<?php
if(!isset($_GET['id']) || (isset($_GET['id']) && !is_numeric($_GET['id']))) {
die();
}
php condition 2
<?php
if(!isset($_GET['id']) || !is_numeric($_GET['id'])) {
die();
}
The difference is that the first one has an unnecessary extra check if $_GET['id'] is set. PHP uses what is called short-circuit boolean evaluation, which means that if the left side of an || is true, the right side doesn't need to be evaluated. So, even in the second example, !is_numeric($_GET['id']) will never get evaluated unless isset($_GET['id']) is true.
Logically these statements are equivalent.
You're basically doing
A || (!A && B)
if A is true, then the rest won't be executed.
If A is false, !A will be true anyway. So the !A is redundant.
Functionally they are the same, but in practice, you don't need the extra condition.
You can see the logical explanation here:
In the first one
It makes three checks which are unnecessary.
In the second it won't catch one of the conditions required
|| means OR - either one of the conditions should evaluate to true
&& means AND - both conditions must be true
To work properly you need this
if (!isset($_GET['id']) && !is_numeric[$_GET['id']])
die();
The first statement does the same thing but it check if $_GET['id'] is set two times which isn't needed.
I actually found out how to solve this particular problem on my own, but it's still driving me crazy wondering why the problem came about to begin with. I had a conditional statement:
if($_SESSION['authenticated'] = 1) {
DOSTUFF;
}
Now prior to this if statement I know that $_SESSION['authenticated'] is empty by using print_r(). However, after executing this code block this conditional statement assigns 1 to $_SESSION['authenticated'], which makes the if statement evaluate to true no matter what! I found a way around this using isset(), but I still have no clue why a conditional statement would assign a value to a variable in the first place when it should only evaluate whether or not the condition is true or false.
Because = is assignment. You want == or === which test for equality. === checks that the operands are both equal and of the same type. == only checks for equality.
You have a semantic (or syntactic) (or typing) error. You should use double equal sign for equality comparison like this:
if($_SESSION['authenticated'] == 1) {
DOSTUFF;
}
If you use single equality sing, that means assignment, and the assigned value gets evaluated in the if statement.
I was wondering how php processes if statements.
If i were to have something such as:
if (isset($_GET['foo']) && $_GET['foo'] != $bar)
If foo isn't set, would it then drop out of the if straight away (as it is an 'and' statement so it can't succeed anyway) or would it also check the second part, rather pointlessly?
What you're describing is known as "short-circuit evaluation".
Most languages work this way, including PHP, so they will evaluate an expression until they are certain of the result, and then stop, so the remainder of the expression would not be evaluated.
As you say, this is the most efficient approach.
However, it can potentially throw a spanner in the works for inexperienced programmers, who nay try something like this:
if(doFirstProcess() && doSecondProcess() {
print "both processes succeeded";
}
In this case, the programmer is expecting both functions to be called, but if the first one returns false, then the second one will not be executed, as the program already knows enough to be certain of the final result of the expression, so it short-circuits the remainder of the expression.
There are a few languages which don't do short-circuit evaluation. VB6 was one example (back in the day). I don't know about VB.Net, but since it's evolved from VB6, I would suspect it would be similar. But aside from that, all other languages that I've worked with have used short-circuit evaluation, including PHP.
There is a section in the PHP manual about this here: http://www.php.net/manual/en/language.operators.logical.php
And you can read more on short circuit evalution here: http://en.wikipedia.org/wiki/Short-circuit_evaluation
Hope that helps.
It's known as short-circuit:
&& and and operators is executed from left to side
If left side is considered false, no reasons to check right side, so it's omitted, false returned
|| and or operators is executed from left to side too
If left side is considered true, no reasons to check right side, so it's omitted, true returned
Manual example:
// foo() will never get called as those operators are short-circuit
$a = (false && foo());
$b = (true || foo());
$c = (false and foo());
$d = (true or foo());
it will leave the if statement after the first expression evaluates to false because this statement can never be true if the first one is false and they are combinded via AND
you can check this very easily. If it wouldn't be like I said, you would get a notice that $_GET['foo'] is not defined
If the first part is false, it stops the if.
Certain operators, most notably && and || are so-called short-circuit operators, meaning that if the result of the operation is clear from the first operand (false or true, respectively), the second operand does not get evaluated.
Edit: Additionally, operands are guaranteed to be evaluated in order, this is not always true of other operators.
Will go out after the first statement.
you can test it:
will print 1:
if(1==1 && $a=1 == 1){
}
print $a;
Will not print a thing:
if(1==2 && $a=1 == 1){
}
print $a;
&& does short-circuit (i.e. returns false as soon as one condition fails).
If it doesn't, then having the isset would be pointless — it exists to prevent errors when trying to compare an undefined value to a string.
If the first check if (isset($_GET['foo']) returns false, the second part will not even be looked into anymore.