Example1:
if(!print("1") || 1){
echo "a";
}else{
echo "b";
}
Output
1b
The Example 1 is printing "1b" instead of "1a". According to me, inside if the final condition should be if(0 || 1) after solving !print("1").
But the Example 2 is printing "1a".
Example 2:
if((!print("1")) || 1){
echo "a";
}else{
echo "b";
}
Output
1a
Can you elaborate, why the or condition in the first statement didn't work.
The key thing here is to realise that print is not a function, and doesn't take arguments in parentheses - the parentheses aren't optional, they're just not part of the syntax at all.
When you write print("1"); the print statement has a single argument, the expression ("1"). That is if course just another way of writing "1" - you could add any number of parentheses and it wouldn't change the value.
So when you write print("1") || 1 the argument to print is the expression ("1") || 1. That expression is evaluated using PHP's type juggling rules as true || true which is true. Then it's passed to print and - completely coincidentally to what you were trying to print - is type juggled to the string "1".
The print statement is then treated as an expression returning true, and the ! makes it false, so the if statement doesn't run.
This is a good reason not to use parentheses next to keywords like print, require, and include - they give the mistaken impression of "attaching" an argument to the keyword.
Related
I want to check whether the length of $a is 0 or if the length is not 0 then check if it is a numeric value in single IF statement in PHP. I tried this but not working
$a = '23bc';
if((strlen($a)===0 || (strlen($a)>0 && ctype_digit($a))) )
{
echo 'Good to Go';
}
else
{
echo 'Bad to Go';
}
I do not want to apply nested conditions here. Is it possible to do it in single IF statement?
I found this question here but this does not answers what I am asking for && (AND) and || (OR) in IF statements
It would be nice to know what your script is trying to achieve beyond using a one-liner in an if conditional concerning an empty string or a numeric string. With cytpe_digit() every character must evaluate as a number to qualify as a numeric string. You get a false result with '23bc' because of the 'bc' portion.
One of the problematic aspects with the script is that one don't know which condition results in a true. One or the other conditions could be true or they could both be false.
See demo: http://3v4l.org/8Pchk.
You could rewrite the code making use of a ternary expression to have a one liner which eliminates the if-else construct, as follows:
<?php
$a = '23bc';
if( strlen( $a ) != 0) {
echo ctype_digit( $a )? "Good to Go\n" : "Bad to Go\n";
}
The following may be more in line with what you're asking. Here's the ultimate one-liner:
<?php
echo ( !strlen($a) || ctype_digit($a) )? "Good to Go\n" : "Bad to Go\n";
Because of the strictness of the identity operator === if $a is null, then you you'll see "Bad to Go. You may either test for equality strlen($a) == 0 or you can be more succinct by using the ! operator (boolean NOT). See demo: http://3v4l.org/7cfV0
Below is something strange, I didn't get
if (print("foo") || print("bar")) {
// "foo" has been printed.
}
Why the output is 1?
Could please explain?
It's because PHP is a ridiculous language. print is not a normal function, it's a language construct. This line is actually parsed as:
if (print (("foo") || print("bar")))
And ("foo") || print("bar") is an expression which evaluates to 1. The string "foo" in a boolean context is true, so the || operator yields 1.
If you explicitly parenthesize the expression the way one would expect it to be parsed:
if ((print("foo")) || (print("bar")))
Then the output is what you would expect:
foo
$var4 = 123;
function fn1($p1)
{
return array('p1' => 1, 'p2' => 2);
}
if ($var1 = fn1(1) AND $var4 == 123)
{
print_r($var1);
}
if ($var2 = fn1(1) && $var4 == 123)
{
print_r($var2);
}
if (($var3 = fn1(1)) && $var4 == 123)
{
print_r($var3);
}
If you run this simple script it will output strange results, at
least for me!! First output from first if expression will result in
an array returned from the function & assigned to the $var1
variable, which is what I'm expecting, well?
Second output from second if expression will result in an integer
'1' assigned to the $var2 variable, which is NOT expected at all!!
Please note that the only changed thing is the logical operator,
I've used '&&' rather than 'AND', that's all!!
Third output from third if expression will result again the expected
array returned from the function & assigned to the $var3 variable,
exactly as the first if expression, but wait: I've just embraced the
assignment statement in the if expression within brackets, while
still using the second if expression code!!
Can anyone explain technically -in details- why this strange behavior? php.net reference links will be appreciated.
I know that '&&' has higher precedence than 'AND' but that doesn't explains it to me!!
PHP: Operator Precendence
&& has a higher precedence than =, so in the second if, you are assigning the value of fn1(1) && $var4 == 123 (true or false) to $var2.
In the first if, AND has a lower precedence than =, so the assignment happens first, then the result is compared.
In the third if, the assignment happens first again because everything in parens gets processed first.
&& has a higher precedence than =, so what's really happening is something more like:
if ($var1 = (fn(1) && $var4 == 123))
So what is really being assigned to $var1 is the boolean result, which is why you get 1.
PHP's AND and && operators both are logical ands, but the and version has a lower binding precedence, see: http://php.net/manual/en/language.operators.precedence.php
I am trying to write would be a simple if condition.
function genderMatch($consumerid1, $consumerid2)
{
$gender1=getGender($consumerid1);
$gender2=getGender($consumerid2);
echo $gender1;
echo $gender2;
if($gender1=$gender2)
echo 1;
return 1;
else
echo 0;
return 0;
}
The output of the getGender function is either a M or F. However, no matter what I do gender1 and gender2 are returned as the same. For example I get this output: MF1
I am currently at a loss, any suggestions?
if ($gender1 = $gender2)
assigns the value of $gender2 to $gender1 and proceeds if the result (i.e. the value of $gender2) evaluates to true (every non-empty string does). You want
if ($gender1 == $gender2)
By the way, the whole function could be written shorter, like this:
function genderMatch($cid1, $cid2) {
return getGender($cid1) == getGender($cid2);
}
You have to put two == for comparison. With only one, as you have right now, you are assigning the value to the first variable.
if($gender1=$gender2)
would become
if($gender1==$gender2)
this:
if($gender1=$gender2)
should be
if($gender1==$gender2)
notice the extra ='s sign. I think you might also need curly brackets for multiple lines of an if/else statement.
Your using the assignment operator = instead of comparsion operators == (equal) or === (identical).
Have a look at PHP operators.
You have some structural problems with your code as well as an assignment instead of a comparison.
Your code should look like this:
function genderMatch($consumerid1, $consumerid2){
$gender1=getGender($consumerid1);
$gender2=getGender($consumerid2);
echo $gender1;
echo $gender2;
if($gender1==$gender2){
echo 1;
return 1;
}else{
echo 0;
return 0;
}
}
Notice the double '=' signs in the if statement. This is a comparison. A single '=' is an assignment. Also, if you want to execute more than 1 line of code with an if/else, you need brackets.
You are using a single = which sets the variable, ie. the value of $gender1 is set to be the value of $gender2.
Use the === operator instead: if($gender1 === $gender2). It is usually a good idea to do strict comparisons rather than loose comparisons.
Read more about operators here: php.net
Another alternative is to use strcmp($gender1, $gender2) == 0. Using a comparer method/function is more common in languages where the string-datatype isnĀ“t treated as a primary data-type, eg. C, Java, C#.
here is what i'm trying to achieve:
if $x is either of these 3 values: 100, 200 or 300 - do something
I'm doing this:
if($x==("100"||"200"||"300"))
{
//do something
}
but //do something is executed even if $x is 400
I noticed that this works:
if($x=="100"||$x=="200"||$x=="300")
{
//do something
}
How is the first block of code different from the second block of code? What am I doing wrong?
The reason why your code isn't working is because the result of the expression:
('100' || '200' || '300')
is always TRUE because the expression contains at least one truthy value.
So, the RHS of the expression is TRUE, while the LHS is a truthy value, therefore the entire expression evaluates to TRUE. The reason why this is happening is because of the == operator, which does loose comparison. If you used ===, the resulting expression would always be FALSE. (unless of course the value of $x is false-y.)
Let's analyze this:
Assuming $x equal '400':
($x == ('100'||'200'||'300'))
// ^ ^
// true true
Make sense now?
Bottom line here is: This is the wrong way of comparing 3 values against a common variable.
My suggestion is that you use in_array:
if(in_array($x, array('100', '200', '300')) {
//do something...
}
you can take all values in array it is working Perfectly.
$x=400;
if(in_array($x, array('100', '200', '300'))) {
echo $x.'is in array';
} else {
echo $x.'is not in array';
}