Handling of 'or' conditions in Ruby vs PHP - 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

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';

What is the difference between the OR and || operator in PHP? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Logical Operators, || or OR?
I've always thought that OR is another way of writing the || operator in PHP. The only way I prefer using OR over || is that it makes the code easier to read since || can be confused with II or 11 or whatever...
One day I stumbled upon this thing though:
<?php
$a = 'string_b';
$active = ($a == 'string_a') OR
($a == 'string_b') OR
($a == 'string_c');
var_dump($active); // Prints FALSE;
?>
Why is this happening?
The only difference is operator priority, see Operator precedence. || has a higher priority than OR.
By the way, var_dump($a) returns null but prints the right thing, string_b.
But, var_dump($active) will indeed produce an unexpected result, false.
In fact, = has higher priority than or, so your code is equivalent to:
($active = ($a == 'string_a')) OR ($a == 'string_b') OR ($a == 'string_c');
It first assigns false to active, then execute the right part of the first OR.
It's the same. But || has higher precedence than OR
http://php.net/manual/en/language.operators.precedence.php
= has a higher precedence than OR. So, $active = ($a == 'string_a') is evaluated first, which is false. Enclose the entire right hand side in it's own set of brackets and you'll get the result you were expecting.
<?php
$a = 'string_b';
$active = (
($a == 'string_a') OR
($a == 'string_b') OR
($a == 'string_c')
);
var_dump($active); // Prints TRUE;
?>

OR in PHP IF Statement

I am having trouble with my IF statement, it is always TRUE although this is incorrect. I'm using an OR operator as there are two possible scenarios I want to capture in the IF statement.
The array string ad_status is "1" but using the below -3 is returned, I'm expecting the IF to be FALSE. If I remove the OR and second statement from the IF, the result of the IF is correct.
What have I done wrong? Thanks.
if(($getadstatus['ad_status'] != "1" || $getadstatus['ad_status'] != "4"))
{
return -3;
exit;
}
Additional:
What I want to do is exit the function (not seen in full here) if ad_status does not equal 1 or 4. If it equals any other value other than 1 or 4, the IF statement should return TRUE and exit.
ad_status could be any value from 0 to 4.
What you are saying is that any value that is not 1 OR is not 4 should return true.
For '1' you get the statement
if( 1 != 1 || 1 != 4)
which translates to
if( false || true )
which is ofcourse true.
What you need is:
if(!($value == 1 || $value==4))
which is the same as (de Morgan's law)
if($value != 1 && $value != 4)
You check:
ad_status != 1 -> FALSE
ad_status != 4 -> TRUE
if (FALSE OR TRUE) is always TRUE.
To be what you expected, replace OR with AND:
if(($getadstatus['ad_status'] != "1" && $getadstatus['ad_status'] != "4"))
{
return -3;
exit;
}
It will always be true as any value can't be both '1' and '4' at the same time.
You should use && operator because use !=. If you want to use || you could write like this:
if (!($getadstatus['ad_status'] == "1" || $getadstatus['ad_status'] == "4"))
You want to use &&
if(($getadstatus['ad_status'] != "1" && $getadstatus['ad_status'] != "4"))
{
return -3;
exit;
}
I personally prefer in_array instead of OR in IF statemements. Eg:
$array = array(1,4);
if (!in_array($getadstatus['ad_status'], $array)) {
// do whatever
}
There are no errors there.
If ad_status == 1 then your second condition will get you into the If
$getadstatus['ad_status'] != "4"
is true therefore you will get return -3;
If i got what you want you should use AND
if ( $a!= 1 AND $a!= 4 )
humm, ok I think I see. I'm attempting to be too clever. I want to use a single IF statement to check for two non related conditions. If ad_status does not equal 1 OR 4, return -3 and exit the function.
Okay, no problem, that can be expressed, just formulate like you write:
$status = $getadstatus['ad_status']; // assign a variable as it makes things easier to read.
if ( !( $status==1 || $status==4 ) )
{
return -3;
}
So the ! (not) should be on the whole OR comparison as you wrote in your sentence. That's probably in code what you had originally in mind. But as the order is important, the other part of your condition needs to be inside brackets to be calculated first, before using the not (!) operator.
Added:
The more sub-conditions are part of a condition or expression, the more complex it gets. But the more often you formulate complex conditions the better you will get with them. To train, you can always split conditions over multiple lines and assign labels (variables) to their part:
$status = $getadstatus['ad_status'];
$statusIs1or4 = $status==1 || $status==4;
$statusIsNot1or4 = !$statusIs1or4;
if ($statusIsNot1or4) return -3;
For production code this might be overuse, but as it's always the authors choice how to write something, you can do whatever the language allows.

EASY! But which conditional statement works

Simple but this has always bothered me. Which is the best way to condition statement?
$foo = '1';
if($foo === '1' || $foo === '2' || $foo === '3')
{
// foo matches
}
or
if($foo === '1' || '2' || '3')
{
// foo matches
}
Which step works and is better. is there a better solution?
The second version will always evaluate to true.
If you want to compact the comparison against multiple alternatives then use:
if (in_array($foo, array('1', '2', '3') )) {
If you want to closely match the exact comparison === then you would however need:
if (is_string($foo) && in_array($foo, array(...))) {
$foo = 1;
if(in_array($foo, array(1, 2, 3))){
//foo matches
}
This is an alternative:
if($foo>0 && $foo<4){
}
Second if statement won't work. PHP doesn't work like that. Any number other than 0 (including negatives) evaluates to true when alone in an if statement. This is why you can do something like if(count($array)) without specifying that count($array) must be greater than 0.
Would be the same as if you had said:
if($foo === 1)
{}
elseif(2) //This will always trigger if $foo !== 1.
{}
elseif(3) //This will never trigger because of the last one
{}
Each condition is it's own self contained condition. Instead of reading it as just "or" or "and" read it as "or if" and "and if". So if $foo is 1 or if 2 or if 3 instead of if $foo is 1 or 2 or 3
If it's just numeric, then amosrivera's solution is the best. If it's for other types of data, then webarto/mario have a good solution.

Is this valid PHP syntax?

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

Categories