If-Else loop output - php

<?php
$x = 1;
if ($x == 2)
print "hi" ;
else if($x = 2)
print $x;
else
print "how are u";
?>
Apologies for this basic question as I am a beginner at php.
I was expecting the else statement to be executed and print "how are u", but it executed the elseif statement and printed '2' instead. May I ask why does $x become assigned to 2? Thanks in advance.

<?php
$x = 1;
if ($x == 2)
print "hi" ;
else if($x = 2) /* you assign $x 2 and it's true */
print $x;
else
print "how are u";
?>

In the elseif you are asigning the number 2 to $x which will always return true. Because of that it will never go to the else block.
Dont use = when doing comparisons but == or ===.
<?php
$x = 1;
if ($x == 2)
print "hi" ;
else if($x == 2)
print $x;
else
print "how are u";
?>
this is the right way to do it. Also it doesnt make sense to check both in if and elseif that $x == 2 since it will never execute the elseif block.
Let me try to explain it better, if you do:
if ($x = 2)
thats will assign 2 to $x and this is then the same as:
if ($x)
since the $x now holds the number 2 this is also the same as:
if (2)
this is always true so it will never go to further checks no matter what the number is.

You are SETTING x=2 in your else if --> else if($x = 2) -- This would be more appropriate .. Check for absolute === .. Then check for truthy == .. IE
<?php
$x = 1;
if ($x === 2)
print "hi" ;
else if($x == 2)
print $x;
else
print "how are u";
?>
Conversely .. You can play with truthy vs absolute by comparing an integer to string too .. Like:
<?php
$x = 2;
if ($x === 2) // Will return true
print "Is absolute integer" ;
else if($x == 2) // Will return true
print "Is truthy integer";
else if($x === '2') // Will return false
print "Is absolute string";
else if($x == '2') // Will return true
print "Is truthy string";
else
print "how are u";
?>
Which will never reach the else .. But you can see how operators can make or break a program ..

This is because = is assignment operator not comparison like ==. That is why $x is assigned value 2 and the else if condition is met and executed.

Related

Why does if($x = 1 && $x == 1) throw error but if ($x == 1 && $x = 2) doesn't in php?

In php the following code gives a warning of undefined variable $x:
if($x = 1 && $x == 1)
I thought it was equivalent to if( ($x = 1) && ($x == 1) ), but that's not the case. I've been told, it's because && has higher precedence than =, which causes the expression to get converted to:
if($x = (1 && ($x == 1)))
So far so good, but now consider:
$x=1; if($x == 1 && $x = 2)
This doesn't throw error. Why doesn't it get converted to:
$x=1; if( (($x == 1) && $x) = 2 )
I've been told thats due to = being right assosiative, but https://www.php.net/manual/en/language.operators.precedence.php says When operators have equal precedence their associativity decides how the operators are grouped.. Here we have =, && and == all being of different precedence.
P.S; My actual code is if($result != false && $res = $stmt->get_result()), which has been copied from some other reputable source, so seems like not using unneeded parenthesis is common in php.
I've played with several conditions and below is what I've got.
First, let's consider that we init $x before if statements to avoid undefined variable notice.
Second, let's confirm the precedence for operators:
== is applied 1st
&& is applied 2nd
= is applied 3rd
This returns true:
$x = 1;
if ($x = 1 && $x == 1) {
echo 'true';
} else {
echo 'false';
}
It goes like ($x = (1 && ($x == 1))) -> ($x = (1 && true)) -> ($x = true) -> true.
If we compare $x to another value than the assigned one we will get false:
$x = 1;
if ($x = 2 && $x == 2) {
echo 'true';
} else {
echo 'false';
}
It goes like ($x = (2 && ($x == 2))) -> ($x = (2 && false)) -> ($x = false) -> false.
The last one returns true:
$x = 1;
if ($x == 1 && $x = 2) {
echo 'true';
} else {
echo 'false';
}
It goes like ((($x == 1) && $x) = 2) -> ((true && $x) = 2) -> (true = 2) -> true.
The last comparison can't be interpreted by PHP so it's an approximate view.
It looks like the last action (true = 2) totally depends on the left operand. If we put $x = 2; we will get (false = 2) -> false.
I'm not sure about the last one and here is the only place were some mistakes can happen.
Otherwise, it looks like precedence works as expected.
Anyway, I always put parenthesis for an assignment action inside if operator (especially inside ternary if) to be sure that I will get what I expect.
I don't think this affects performance or readability too much, but it may prevent some logical errors.
UPDATE:
Concering your code if($result != false && $res = $stmt->get_result()) it's not correct to compare it to if($x == 1 && $x = 2) because in your code are two different variables.
In this case logical operator will not call the second part at all if the fisrt one is false, see the 1st example here
UPDATE-2:
After the discussion under this answer we can see that the last conditions ($x == 1 && $x = 2) work like like (($x == 1) && ($x = 2)) -> ((1 == 1) && 2) -> true and $x becomes 2 after it.

How can I make a for statement have an else

I have a databse that has food reviews on it, and I want to show if a food is vegetarian or not.
I want to add a echo "No"; but I don't know how.
I've tried using else, but it doesn't show. I've also tried <?php for($x=1;
Here is my code:
<p>Vegetarian: <span class="sub_heading"><?php for($x=0; $x < $find_rs['Vegetarian']; $x++)
{
echo "Yes";
}
; ?></span></p>
I want it to show no if it is 0 and yes if it is 1
<p>
Vegetarian:
<span class="sub_heading"><?= $find_rs['Vegetarian'] ? "Yes" : "No"?></span>
</p>
Simply add an if conditional inside of your loop that checks against the value of $x:
for ($x=0; $x < $find_rs['Vegetarian']; $x++) {
if ($x == 1) {
echo "Yes";
}
else if ($x == 0) {
echo "No";
}
else {
echo "x wasn't either 0 or 1 -- x was $x";
}
}
Note that the final else condition will output the value of $x due to the use of double-quotes.
if the condition only 2, just using if else statement,
<?php
for($x=0; $x < $find_rs['Vegetarian']; $x++){
if($x == 1){echo 'Yes';}else{echo 'No';}
}
?>

how works or operator in if statements and print

I have two questions
1) how can i make php to check getnext() function,if it exists or what value it has ???
$a = 1;
if($a == 1 or getnext()== 1){
echo "yeap"; //this works
}
2)i want to write condition -- if $a or $b is equal to 1 , print the variable name that has the value of 1.
Is it possible to do in php ??can i do it this way???
if($a ==1 or $b==1){
print($a or $b);
}
thanks in advance:)
You could for example do as follows :
if($a ==1 || $b==1){
print (($a == 1)? $a : $b);
}
For your first question,
your getnext() function must be return some valid integer value then only you can compare it with integer 1.
for second,
You should write
if($a == 1 && $b == 1){
echo 'both are 1';
}
else if($a == 1){
echo '$a is 1';
}
else if($b == 1){
echo '$b is 1';
}else{
// both are not 1
}
also see this links,
logical operators or vs || (double pipe) in php
PHP: return value from function and echo it directly?
You write condition? You use if and else, if no else in if you put return. Goodluck

Switch evaluations

I recently got into an argument over how switch handles comparisons, and need help settling it.
If I write a switch such as:
switch ($x){
case ($x > 5):
echo "foo";
break;
case ($x < 5):
echo "bar";
break;
default:
echo "five";
break;
}
Which if statement is it equivalent to? A or B?
// A
if ($x > 5) {
echo "foo";
} elseif ($x < 5) {
echo "bar";
} else {
echo "five";
}
// B
if ($x == ($x > 5)) {
echo "foo";
} elseif ($x == ($x < 5)) {
echo "bar";
} else {
echo "five";
}
To everyone, let me clarify:
It is equivalent to B.
It is not "both", it is not sometimes its one, sometimes it is the other, it is always B. To understand why you sometimes see results that indicate that it might be A, you need to understand how type coercion works in PHP.
If you pass in a falsey value to the "argument" of switch and you use expressions in your cases that result in a boolean value, they will only match if your expression evaluates to FALSE.
switch is basically a huge if/elseif tree that performs loose comparisons (== instead of ===) between the value passed to switch (the left side of the expression) and the expression in the cases (the right side).
This can be proved quite nicely with a variation on your code:
$x = 0;
switch ($x) {
case $x > -1: // This is TRUE, but 0 == FALSE so this won't match
echo "case 1";
case $x == -1: // This is FALSE, and 0 == FALSE so this will match
echo "case 2";
}
And if we convert that to the two if/elseif trees:
A:
$x = 0;
if ($x > -1) {
// It matches here
echo "case 1";
} else if ($x == -1) {
// and not here
echo "case 2";
}
B:
$x = 0;
if ($x == ($x > -1)) {
// It doesn't match here
echo "case 1";
} else if ($x == ($x == -1)) {
// ..but here instead
echo "case 2";
}
Your example is equivalent to B.
If you want to use comparison into your switch (and be equivalent to A), you could write this:
switch (true) { // Use true instead of $x
case ($x > 5):
echo "foo";
break;
case ($x < 5):
echo "bar";
break;
default:
echo "five";
break;
}
That switch case is equivalent to B
Edit :
If we take for example that $x is equal to 0 :
$x > 5 will evaluate to false (and 0 evaluates to false too), so the first if will print bar, but the second one will print foo.
The switch will be transformed to something like this :
switch ($x){
case false:
echo "foo";
break;
case true:
echo "bar";
break;
default:
echo "five";
break;
}
and that will print foo (same as B)
Edit 2 :
I tried it so that gave me :
with $x = 0 => switch (foo), if A (bar), if B (foo)
with $x = 5 => switch (five), if A (five), if B (five)
with $x = 7 => switch (foo), if A (foo), if B (foo)

how to change the while loop condition depending on stuff?

by this question what i mean is that if, by example, someone's username is "bob" then the while loop condition will be ($i < 10), and if the username is something else then the while loop condition will be ($i > 10)
if($username == "bob")
{
//make this while loop condition: ($i < 10)
// it means: while($i <10){ so stuff}
}
else
{
//make the while loop condition: ($i >10)
}
Make do_stuff a function, then this is perfectly readable (although special-casing 'bob' seems doubtable at best).
if($username == "bob")
{
while($i<10) {
do_stuff();
}
}
else
{
while($i>10) {
do_stuff();
}
}
while( ($username == 'bob' && $i <10 ) XOR $i > 10){}
$username == 'bob' will be evaluated first if it comes out to be true then $i < 10 is evaluated.
$var1 XOR $var2 is true only when one of $var1, $var2 is true but not both.
But I myself will go with this.
Try making two different while loops within the if and else blocks.
Is this what you mean? You can just take a different path depending on the success or failure of the if. If the code inside is the same, just call a method to avoid duplicating it.
if($username == "bob")
{
//make this while loop condition: ($i < 10)
// it means: while($i <10){ so stuff}
while ($i < 10) {
call_method();
}
}
else
{
while ($i > 10) {
call_method();
}
}
To keep your code simple:
if($username == "bob")
{
while ($i<10){
}
}
else
{
while ($i>10){
}
}
There are other better ways to handle it but they may make your code difficult to understand like using eval which I dont like.

Categories