Is this valid PHP syntax? - php

if ($var == ($var1 || $var2))
{
...
}
I am considering using this, but am ont sure if it is valid, and there doesn't seem to be somewhere to check.
It seems logically consistent to me but am not sure, and I don't have something to test it on close by.
If it is valid, what other mainstream languages support this sort of construct.
EDIT: The comparison is valid, but not in the way I was thinking.
What I was trying to do was actually the in_array() function, which I just discovered.

Your code is syntactical valid but semantical probably not what you wanted.
Because $var1 || $var2 is a boolean expression and always yields true or false. And then $var is compared to the result of that boolean expression. So $var is always compared to either true or false and not to $var1 or $var2 (that’s what you’re have probably expected). So it’s not a shorthand to ($var == $var1) || ($var == $var2).
Now as you already noted yourself, in_array is a solution to this problem if you don’t want to write expressions like ($var == $var1) || ($var == $var2), especially when you have an arbitrary number of values you want to compare to:
in_array($var, array($var1, $var2))
Which is equivalent to:
($var == $var1) || ($var == $var2)
If you need a strict comparison (using === rather than ==), set the third parameter to true:
in_array($var, array($var1, $var2), true)
Which is now equivalent to:
($var === $var1) || ($var === $var2)

Yes, the corrected version is valid syntax:
if ($var == ($var1 || $var2))
Question is, what does it mean?
It will compare the result of the expression ($var1 || $var2) which will be a boolean, to the value of $var.
And, as mentioned, php -l file.php will tell you if there are any syntax errors.
Edit:
Consider this:
$var1 = 1;
$var2 = 2;
echo var_dump(($var1 || $var2));
Result is:
bool(true)

You can use the command php -l filename.php from the command line to check for syntax errors.

As George Marian says, it's missing a closing parenthesis so would throw a syntax error. It's otherwise valid, though, so I can't see that it's the logical OR construct itself that you're unsure about. It's used in several languages, including javascript.

your corrected example is valid and will be TRUE is $var is TRUE and either $var1 or $var2 is TRUE .. OR . if $var, $var1 and $var2 are all FALSE

Related

Ternary operator with multiple conditions

Hello I am trying to properly format ternary operator to be using multiple conditions in php:
$result = ($var !== 1 || $var !== 2) ? '' : 'default';
The problem is that in this format I always get not true even iv the $var is 1 or 2. With one condition for example $var == 0 it is working fine. Any help will be welcome.
This statement will always be true:
($var !== 1 || $var !== 2)
Because $var can never simultaneously be both values, it will always not be at least one of the two values. Which satisfies the || operator.
If you want to know whether $var is one of the two values:
($var === 1 || $var === 2)
If you want to know if $var is neither of the two values, you can negate the condition:
(!($var === 1 || $var === 2))
Or individually negate the operators in the condition and use && instead of || (since all conditions need to be met to prove the negative, instead of just one condition to prove the positive):
($var !== 1 && $var !== 2)
Depending on readability and personal preference.
If $var is 0 , $result is "default" but 1 and 2 enter in condition, both are different from both and always enter.
$result = ($var !== 1 && $var !== 2) ? '' : 'default';

Evaluation and assignment in if statement

I'm wondering, will this work with any major PHP versions?
if ($foo != $bar && '' != $str = some_function($some_variable))
echo $str;
The some_function($some_variable) returns a string, which is assigned to the $str variable and then checked if is an empty string. The $str variable is used later of course.
Will be the output of the some_function assigned to the $str variable in every major PHP version (>5)? I couldn't find any information on this. Thanks.
I'm currently running 5.4 and it's working.
Edit: To avoid further confusion, the $foo != $bar precedes the other expression because the $str variable is only used inside the if statement. Sorry, I forgot to clarify that.
Yes it does work, but to get it working like you want you have to put brackets around the assignment, because the comparison has a higher precedence then the assignment! (operator precedence)
Also if $foo != $bar is false the $str would never been initialize so also change the order, so that it get's assigned ever time.
So use this:
if ('' !== ($str = some_function($some_variable)) && $foo != $bar)
//^^^ ^ See here And here^
//| '!==' to also check the type
I would not see why this would not work in any PHP version (> 5).
Tested here: http://sandbox.onlinephpfunctions.com/code/a295189c50c191bbd0241d4e8ea4e3081cdb40ae
Worked with all the versions from 4.4.9 and up.
Note: Because you are using the && operator, the code after the && will not be run if $foo != $bar already returns false, since the second expression cannot change the outcome of the && operator, therefore it will simply ignore it.
If the assignment is intented to always take place, then change the order of the expressions.
if ('' != $str = some_function($some_variable) && $foo != $bar)
echo $str;
Why don't you make it clear and not confusing by using brackets and curly braces. Example:
if (($foo != $bar) && '' != ($str = some_function($some_variable)) ) {
echo $str;
}

PHP "or" syntax statement

Moving over to PHP from another language and still getting used to the syntax...
What's the proper way to write this statement? The manual on logical operators leaves something to be desired..
if($var !== '5283180' or '1234567')
Generally, comparison is by using == and the reverse is !=. But if you want to compare values along with its data type, then you can use === and the reverse is !==.
Please refer to the documentation for more information.
You can use the following:
if($var!='5283180' || $var!='1234567')
Try this
if($var != '5283180' || $var != '1234567')
PHP's or functions identically to the normal ||, but has a lower binding precedence. As such, these two statements:
$foo = ($bar != 'baz') or 'qux';
$foo = ($bar != 'baz') || 'qux';
might appear to be otherwise identical, but the order of execution is actually quite
different. For the or version, it's executed as:
($foo = ($bar != 'baz')) or 'qux';
- inequality test is performed
- result of the test is assigned to $foo
- result of the test is ORed with the string 'qux';
For the || version:
$foo = (($bar != 'baz') || 'qux');
- inquality test is performed
- result of test is ||'d with 'qux'
- result of the || is assigned to $foo.
To build on the others, as the OP mentioned they are new to PHP, there is a couple things to be considered.
First off, the PHP or that you're looking for is the double line (||) and each item must be a statement on each side of the ||.
if ( $var !== '5283180' || $var !== '1234567')
addition:
As mentioned in the PHP Manual
The or operator is the same as the || operator but takes a much lower precedence.
Such as the given example (from manual):
// The constant false is assigned to $f and then true is ignored
//Acts like: (($f = false) or true)
$f = false or true;
Now as mentioned, there is the general comparison (== or 'Equal') and the type comparison (=== or 'Identical'), with both having the reverse (not). In the given example, the test will check that $var is not identical to the values.
From PHP Manual:
$a !== $b | Not identical | TRUE if $a is not equal to $b, or they are not of the same type.
With this said, double check that this is what you're actually trying to accomplish. Most likely you're looking for !=.

PHP Logical Operators precedence affects variable assignment results strangely

$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

Handling of 'or' conditions in Ruby vs PHP

I'm not sure what to call this, so I'll give an example.
In PHP
1==2 || 2 returns 1 or true
In Ruby
1==2 || 2 returns 2 (The second statement if the first evaluates to false).
Is there any short way to implement similar thing in PHP?
How about
1==2 ? 1==2 : 2
or in PHP 5.3
1==2 ?: 2
In PHP, the result of boolean expressions is always a boolean. So 1==2 || 2 gives true.
The best thing I can think of is
($var = 1 == 2) || ($var = 2)
Then $var will be 2.
Depending on the answer to Matchu's question, you may want:
(($var = 1) == 1) || ($var = 2)
or
($var = 1 == 1) || ($var = 2)
How about 1 == 2 or 2?
However, the result might not be the same if you print directly, so you need to put the result inside a variable. Take this example:
$result = "a" or 2;
var_dump($result); // prints string(1) "a"
var_dump("a" or 2); // prints bool(true)
Take a look here: http://www.php.net/manual/en/language.operators.logical.php

Categories