I am trying to set up a simple php/mysql database on my website and the example has a line that says:
if (!$searchtype || !?searchterm) {
What are the ||??? I tried to copy and paste them but they cause syntax errors. Noob question I know, but would love an answer nonetheless!
its ||(OR) logical operator
$a || $b Or TRUE if either/both $a or $b is TRUE.
and it should be
if (!$searchtype || !searchterm) {
as in op this Comment you can write this by
I think the code actually is :
if (!$searchtype || !$searchterm) {
|| means OR operator, meaning conditions is satisfied if either of the condition is true.
Its an OR logical operator for handling conditions:
Ex :
$a || $b
Or TRUE if either $a or $b is TRUE.
See : http://php.net/manual/en/language.operators.logical.php
for more details
Related
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 !=.
I'm a bit of an optimization freak (at least by my definition) and this question has been bugging me for quite a while.
I'm wondering if PHP does some optimization on && and ||:
Take the following example:
$a = "apple";
$b = "orange";
if ($a == "orange" && $b == "orange") {
//do stuff
}
When that code executes, it will check if $a is equal to "orange." In this case it isn't. However, there is an && operator. Since the first part ($a == "orange") already returned false, will PHP still check if $b is equal to "orange?"
I have the same question for ||:
$a = "orange";
$b = "orange";
if ($a == "orange" || $b == "orange") {
//do stuff
}
When it checks if $a is equal to "orange," it returns true. Since that would make the || operator return true, will PHP even check the second part of the || (since we already know it will be true)?
Hopefully I am making sense here, and hopefully somebody has an answer for me. Thank you!
PHP uses short circuit evaluation with binary conditionals (such as &&, || or their constant equivalents), so if the result of evaluating the LHS means the RHS isn't necessary, it won't.
For example...
method_exists($obj, 'func') AND $obj->func();
...is an exploitation of this fact. The RHS will only be evaluated if the LHS returns a truthy value in this example. The logic makes sense here, as you only want to call a method if it exists (so long as you're not using __call(), but that's another story).
You can also use OR in a similar fashion.
defined('BASE_PATH') OR die('Restricted access to this file.');
This pattern is used often as the first line in PHP files which are meant to be included and not accessed directly. If the BASE_PATH constant does not exist, the LHS is falsy so it executes the RHS, which die()s the script.
Yes, PHP short-circuits the && and || operators, meaning that no, the right operand won't be evaluated if the value of the left operand means that it doesn't need to be evaluated. There's no need to optimize them. You can test it like this:
function one() {
echo "One";
return false;
}
function two() {
echo "Two";
return true;
}
one() && two(); // Outputs One
echo "\n";
two() || one(); // Outputs Two
Here's a demo. If there were no short-circuiting, you'd get:
OneTwo
TwoOne
I know this must be a simple question, but I know that in PHP in a statement like this
if ($a && $b) { do something }
if $a is false PHP doesn't even check $b
Well is the same thing true about OR so
if ($a || $b) { do something }
If $a is true, does it still check $b
I know this is elementary stuff, but I can't find the answer anywhere... Thanks
Evaluation of logical expressions is stopped as soon as the result is known.
logical operators
See Example 1 on the Logical Operators page in the manual.
// --------------------
// foo() will never get called as those operators are short-circuit
$a = (false && foo());
$b = (true || foo());
$c = (false and foo());
$d = (true or foo());
Look at this example:
function foo1() {
echo "blub1\n";
return true;
}
function foo2() {
echo "blub2\n";
return false;
}
if (foo1() || foo2()) {
echo "end.";
}
$b / foo2() isnt checked.
Demo here: codepad.org
If at least one OR Operand is true, there is no need to go further and check the other operands and the whole thing will evaluate to true.
(a || b || c || d || e ||...) will be TRUE if at least one of the operands is true, thus once I found one operand to be true I do not need to check the following operands.
This logic applies everywhere, PHP, JAVA, C...
If you know your truth tables fairly well, then you can probably figure it out yourself. As others have said, PHP will evaluate until it is certain of an outcome. In the case of OR, only one has to be true for the statement to return true. So PHP evaluates until it finds a true value. If it doesn't find one, the statement evaluates to false.
<?php
if(true && willGetCalled()) {}
if(false && wontGetCalled()) {}
if(true || wontGetCalled()) {}
if(false || willGetCalled()) {}
?>
return (empty($neededRole) || strcasecmp($role, 'admin') == 0 || strcasecmp($role, $neededRole) == 0);
What exactly does the || mean in this statement? Can someone put this in english for me.
I promise I've googled this but I guess I don't know what to google for because I can't find anything.
thanks:)
It is the OR logicial operator.
http://www.php.net/manual/en/language.operators.logical.php
Googling symbols is always hard. Don't worry: || means or in the statement. Don't confuse it for Xor which is slightly different:
or or || is meant as A or B or A + B
xor is meant as A or B, not both
References:
Logical operator
This is an OR operator. It is true if any of it's 'parameters' is true.
|| means or.
It's a logical or, so it's true if at least one of the terms is true, false otherwise.
I have a codebase where developers decided to use AND and OR instead of && and ||.
I know that there is a difference in operators' precedence (&& goes before and), but with the given framework (PrestaShop to be precise) it is clearly not a reason.
Which version are you using? Is and more readable than &&? Or is there no difference?
If you use AND and OR, you'll eventually get tripped up by something like this:
$this_one = true;
$that = false;
$truthiness = $this_one and $that;
Want to guess what $truthiness equals?
If you said false... bzzzt, sorry, wrong!
$truthiness above has the value true. Why? = has a higher precedence than and. The addition of parentheses to show the implicit order makes this clearer:
($truthiness = $this_one) and $that
If you used && instead of and in the first code example, it would work as expected and be false.
As discussed in the comments below, this also works to get the correct value, as parentheses have higher precedence than =:
$truthiness = ($this_one and $that)
Depending on how it's being used, it might be necessary and even handy.
http://php.net/manual/en/language.operators.logical.php
// "||" has a greater precedence than "or"
// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;
// The constant false is assigned to $f and then true is ignored
// Acts like: (($f = false) or true)
$f = false or true;
But in most cases it seems like more of a developer taste thing, like every occurrence of this that I've seen in CodeIgniter framework like #Sarfraz has mentioned.
Since and has lower precedence than = you can use it in condition assignment:
if ($var = true && false) // Compare true with false and assign to $var
if ($var = true and false) // Assign true to $var and compare $var to false
For safety, I always parenthesise my comparisons and space them out. That way, I don't have to rely on operator precedence:
if(
((i==0) && (b==2))
||
((c==3) && !(f==5))
)
Precedence differs between && and and (&& has higher precedence than and), something that causes confusion when combined with a ternary operator. For instance,
$predA && $predB ? "foo" : "bar"
will return a string whereas
$predA and $predB ? "foo" : "bar"
will return a boolean.
Let me explain the difference between βandβ - β&&β - "&".
"&&" and "and" both are logical AND operations and they do the same thing, but the operator precedence is different.
The precedence (priority) of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator.
Mixing them together in single operation, could give you unexpected results in some cases
I recommend always using &&, but that's your choice.
On the other hand "&" is a bitwise AND operation. It's used for the evaluation and manipulation of specific bits within the integer value.
Example if you do (14 & 7) the result would be 6.
7 = 0111
14 = 1110
------------
= 0110 == 6
which version are you using?
If the coding standards for the particular codebase I am writing code for specifies which operator should be used, I'll definitely use that. If not, and the code dictates which should be used (not often, can be easily worked around) then I'll use that. Otherwise, probably &&.
Is 'and' more readable than '&&'?
Is it more readable to you. The answer is yes and no depending on many factors including the code around the operator and indeed the person reading it!
|| there is ~ difference?
Yes. See logical operators for || and bitwise operators for ~.
Another nice example using if statements without = assignment operations.
if (true || true && false); // is the same as:
if (true || (true && false)); // TRUE
and
if (true || true AND false); // is the same as:
if ((true || true) && false); // FALSE
because AND has a lower precedence and thus || a higher precedence.
These are different in the cases of true, false, false and true, true, false.
See https://ideone.com/lsqovs for en elaborate example.
I guess it's a matter of taste, although (mistakenly) mixing them up might cause some undesired behaviors:
true && false || false; // returns false
true and false || false; // returns true
Hence, using && and || is safer for they have the highest precedence. In what regards to readability, I'd say these operators are universal enough.
UPDATE: About the comments saying that both operations return false ... well, in fact the code above does not return anything, I'm sorry for the ambiguity. To clarify: the behavior in the second case depends on how the result of the operation is used. Observe how the precedence of operators comes into play here:
var_dump(true and false || false); // bool(false)
$a = true and false || false; var_dump($a); // bool(true)
The reason why $a === true is because the assignment operator has precedence over any logical operator, as already very well explained in other answers.
Here's a little counter example:
$a = true;
$b = true;
$c = $a & $b;
var_dump(true === $c);
output:
bool(false)
I'd say this kind of typo is far more likely to cause insidious problems (in much the same way as = vs ==) and is far less likely to be noticed than adn/ro typos which will flag as syntax errors. I also find and/or is much easier to read. FWIW, most PHP frameworks that express a preference (most don't) specify and/or. I've also never run into a real, non-contrived case where it would have mattered.