Simple IF/ELSEIF not comparing properly - php

I'm new to PHP and this was asked before but the answers just won't cut it in my scenario.
I have this piece of code:
if ($node->field_available_for_payment[LANGUAGE_NONE][0]['value']==0){
} elseif($node->field_available_for_payment[LANGUAGE_NONE][0]['value']==1){
$status="awaitingapproval";
} elseif (3===3){
$status="paid";
} elseif ($node->field_shipped[LANGUAGE_NONE][0]['value']==1){
$status="shipped";
}
var_dump($status);
I get back value awaitingapproval (the first if/elseif evaluate to
TRUE).
However shouldn't I be getting back 'paid' instead since the 3===3 comparison evaluates to TRUE?
as well?
All the other S.0 answers regarding this type of questions mention the '=' operator vs '==' which is correct in my code.

Control structures like if/else stop executing once a truthy statement is reached. Since the first block is true the other blocks are never evaluated.
If that first block should ever fail, (i.e. evaluate to false) then your second statement will always evaluate to true and the code will be executed.

Related

Why =! seems a legit condition in php?

I just experienced a sort of bug while coding in Php:
I was writing some condition like this:
if($showPrice != 0){
$worksheet->mergeCells('A'.$rowCount.':F'.$rowCount);
$worksheet->SetCellValue('A'.$rowCount, 'Total Weight');
$worksheet->SetCellValue('G'.$rowCount, $totalWeight);
}else{
$worksheet->mergeCells('A'.$rowCount.':D'.$rowCount);
$worksheet->SetCellValue('A'.$rowCount, 'Total Weight');
$worksheet->SetCellValue('E'.$rowCount, $totalWeight);
}
I noticed that instead of writing != as I should, I was wrongly writing =! without getting any error.
What could be the reason of this?
You didn't find any bug in PHP. You found a bug in your program and in your knowledge about the PHP.
$x =! 0 is, in fact, $x = !0.
! is the logical NOT operator.
0 is evaluated as FALSE in boolean context, consequently !0 is TRUE.
$x = ... is a regular assignment. As any assignment, it does two things:
stores the value of the right-hand side expression into the left-hand side variable; here the expression is !0 that, as explained above, is evaluated to TRUE;
the value of the entire expression ($x = !0) is the value of $x after the assignment (TRUE as described).
When the assignment it is used as a statement, its value is discarded. When it is used as a condition (in a for, while, if, switch statement), its value is used to control the execution of the code.
Here, if($showPrice =! 0) always takes the if branch (and never the else branch) because the value of the $showPrice = !0 expression is always TRUE as explained above.
More, the value of $showPrice also becomes TRUE after this statement is evaluated.
Two bugs in a single line of code.
From the PHP's point of view the code is perfectly valid and, even if it is unusual, maybe it represents the programmer's intention. The interpreter doesn't have any reason to complain about it. It can be, however, detected and flagged as a possible error by static code analysis tools and some PHP IDEs.

How does PHP evaluate compound if statements?

Given the nested if statements below:
if(file_exists($fullPathToSomeFile)) {
if(is_readable($fullPathToSomeFile)) {
include($fullPathToSomeFile);
}
}
how does this differ from:
if(file_exists($fullPathToSomeFile) && is_readable($fullPathToSomeFile)) {
include($fullPathToSomeFile);
}
Specifically, I want to know how PHP will treat is_readable() if $fullPathToSomeFile does not exist (first conditional fails).
At some point, I started nesting these because using the one-liner version was throwing errors under some conditions. It seems to me that using any 'and' will ask PHP to evaluate everything regardless of the true / false result.
What I really want is to have it stop evaluating when it reaches the first false, thereby preventing warnings or fatal errors when the conditional fails. Doing it nested (first example) guarantees this, but nested if statements are harder to read and maintain.
What's the current best practice for handling this?
Specifically, I want to know how PHP will treat is_readable() if $fullPathToSomeFile does not exist (first conditional fails).
PHP uses short-circuit evaluation for the && operator. That is, if the first condition in an expression like if (A && B) fails, it is obvious the the whole condition will be false. Thus, the second condition B does not need to be evaluated to determine the result and will not be evaluated at all.
Take for example the following code:
<?php
function hey()
{
echo "Hey there!\n";
return true;
}
if (false && hey())
{
echo "Statement evaluated to true.\n";
}
else
{
echo "Statement evaluated to false.\n";
}
?>
This will echo only one line ("Statement evaluated to false."), but not "Hey there!", because the second part of the if condition will not be evaluated.

PHP conditional statement using $_SESSION assigns value, but why?

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.

What does while (true){ mean in PHP?

I've seen this code, and I've no idea what it means.
while(true){
echo "Hello world";
}
I know what a while loop is, but what does while(true) mean? How many times will it executed. Is this not an infinite loop?
Although is an infinite loop you can exit it using break. It is useful when waiting for something to happen but you don't exactly know the number of iteration that will get you there.
Yes, this is an infinite loop.
The explicit version would be
while (true == true)
This is indeed (as stated already) an infinite loop and usually contains code which ends itself by using a 'break' / 'exit' statement.
Lots of daemons use this way of having a PHP process continue working until some external situation has changed. (i.e. killing it by removing a .pid file / sending a HUP etc etc)
Please referes to the PHP documentation currently at: http://www.w3schools.com/php/php_looping.asp
The while loop executes a block of code as long as the specified condition is true.
while (expression) {
statement(s)
}
The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the
while statement executes the statement(s) in the while block. The
while statement continues testing the expression and executing its
block until the expression evaluates to false.
As a consequence, the code:
while (true) {
statement(s)
}
will execute the statements indefinitely because "true" is a boolean expression that, as you can expect, is always true.
As already mentioned by #elzo-valugi, this loop can be interrupted using a break (or exit):
while (true) {
statement(s)
if (condition) {
break;
}
}
It is indeed an infinite loop.

Strange variable assignment

I was studying some code I found on the web recently, and came across this php syntax:
<?php $framecharset && $frame['charset'] = $framecharset; ?>
Can someone explain what is going on in this line of code?
What variable(s) are being assigned what value(s), and what is the purpose of the && operator, in that location of the statement?
Thanks!
Pat
Ah, I just wrote a blog post about this idiom in javascript:
http://www.mcphersonindustries.com/
Basically it's testing to see that $framecharset exists, and then tries to assign it to $frame['charset'] if it is non-null.
The way it works is that interpreters are lazy. Both sides of an && statement need to be true to continue. When it encounters a false value followed by &&, it stops. It doesn't continue evaluating (so in this case the assignment won't occur if $framecharset is false or null).
Some people will even put the more "expensive" half of a boolean expression after the &&, so that if the first condition isn't true, then the expensive bit won't ever be processed. It's arguable how much this actually might save, but it uses the same principle.
&& in PHP is short-circuited, which means the RHS will not be evaluated if the LHS evaluates to be false, because the result will always be false.
Your code:
$framecharset && $frame['charset'] = $framecharset;
is equivalent to :
if($framecharset) {
$frame['charset'] = $framecharset;
}
Which assigns the value of $framecharset as value to the array key charset only if the value evaluates to be true and in PHP
All strings are true except for two: a string containing nothing at all and a string containing only the character 0

Categories