Difference between & and && in PHP - php

I am confused with & and &&. I have two PHP books. One says that they are same, but the another says they are different. I thought they are same as well.
Aren't they same?

& is bitwise AND. See Bitwise Operators. Assuming you do 14 & 7:
14 = 1110
7 = 0111
---------
14 & 7 = 0110 = 6
&& is logical AND. See Logical Operators. Consider this truth table:
$a $b $a && $b
false false false
false true false
true false false
true true true

The other answers are correct, but incomplete. A key feature of logical AND is that it short-circuits, meaning the second operand is only evaluated if necessary. The PHP manual gives the following example to illustrate:
$a = (false && foo());
foo will never be called, since the result is known after evaluating false. On the other hand with
$a = (false & foo());
foo will be called (also, the result is 0 rather than false).

Matthew's answer about how Logical And && operator is the biggest difference; logical comparison will stop when it will find something that breaks the chain. In addition, one more big difference it the result type/value.
tl;dr
By using the Logical And &&, it will always return a Boolean type/value, true or false.
false & 1 // int(0)
false && 1 // bool(false)
It is important to use Boolean type/values when returning a function with a logical result, because someone can use the Identical comparison operator === to compare the results (which is high likely to happen) and it will fail if you use something like this:
(false & 1) === false // bool(false)
(true & true) === true // bool(false)
Never use Bitwise And & when you need to make a logical comparison and especially when returning values from functions with logical results. Instead use the Logical And &&:
(false && 1) === false // bool(true)
(true && true) === true // bool(true)
When comparing characters, Logical And && will always result to true, even with NUL character, unless if it's converted to an integer:
'A' && 'B' // bool(true)
'A' && 0 // bool(false)
'A' && '\0' // bool(true)
'A' && (int)'\0' // bool(false)
If you use the Bitwise And & with characters, it will result the character corresponding to the Bitwise And operation between those two characters:
'A' & 'B' // string(1) "#"
01000001 // ASCII 'A'
&
01000010 // ASCII 'B'
=
01000000 // ASCII '#'
Beware the usage of the Bitwise And & when using with types other than Integers and Characters (which are special kind of integers). For example, if you use it with real numbers float/double, then it can result to 0 even if both operands are NOT 0:
1.0 & 1.0 // int(1)
2.0 & 1.0 // int(0)
1.0 && 1.0 // bool(true)
2.0 && 1.0 // bool(true)
In addition, if we go at assembly instructions level, we can see that difference and how the compiler manages to handle so the Logical And && uses cmp <var>, 0 to compare and does not continue executing if one operand fails; Bitwise And uses and <var1>, <var2> to make a bitwise result and then test if it's of 0 value. I know this question is tagged for php and php behavior may be different than c, but I'll use a small c program to demonstrate how compiler behaves when using Logical and Bitwise And.
Let's assume we have a program in c that uses both Bitwise and Logical And:
int a = 0;
int b = 1;
int c = 2;
if (a & b)
c = 3;
if (a && b)
c = 4;
The compiler will generate the following assembly opcodes (W32Dasm result for x86; I have changed the memory addresses with <variable> names for simplicity and to be more understandable):
:0229 mov <a>, 0
:0230 mov <b>, 1
:0237 mov <c>, 2
// if (a & b) begins
:023E mov eax, <a>
:0241 and eax, <b> // a bitwise and b, result stored to eax
:0244 test eax, eax // test eax and set ZeroFlag if equals to 0
:0246 je 024F // >--- Jump if ZeroFlag is set
:0248 mov <c>, 3 // | or set c = 3
// if (a && b) begins |
:024F cmp <a>, 0 // <--- compare a to 0 and sets ZeroFlag if difference is 0
:0253 je 0262 // >--- Jump if ZeroFlag is set (a == 0)
:0255 cmp <b>, 0 // | compare b to 0 and sets ZeroFlag if differemce is 0
:0259 je 0262 // | >--- Jump if ZeroFlag is set (b == 0)
:025B mov <c>, 4 // | | or set c = 4
:0262 <program continues> // <--- <---
The compiler not only uses different instructions to compare between the Logical and Bitwaise And, but at the line :0253 in if (a && b) logical comparison, we see that if a == 0 then it jumps and does not check for the rest operands.
So, I disagree to animuson's comment:
They are both the same thing, they're just used for two different
things to accomplish the same task. – animuson Mar 4 '10 at 1:42
They are not the same thing and both are/(should be) used for specific tasks depending on the programs' logic/flow.

AND operation:
& -> will do the bitwise AND operation , it just doing operation based on
the bit values.
&& -> It will do logical AND operation. It is just the check the values is
true or false. Based on the boolean value , it will evaluation the
expression

As the others are saying, a single & is bit-wise. It basically converts the left-hand value into its bits representation, and the right hand side into bits representation as well, then performs logical AND between them and outputs the result.
Double && is either true or false, (in some languages 0 or 1) if both left and right side are true (or non-zero).
I'd also add that this is not just in PHP. It is like that in many many other languages as well, like C, Java, Ruby, etc.

&& is & performed on operands reduced to either 1 or 0.
(In other words, && is a bitwise operator under the caveat that it changes its operands. That is, logical operations are a subset of bitwise operations.)

Related

php AND, OR operators in If statements

I am new to programming so please don't judge me. This question is simple concept knowledge that I have somehow missed. My question is, do brackets make difference when you are using AND and OR operators? For example,
if ( x == 1 && ( y == 1 || y == 2 ) ){
// do something
}
Basically, what I want to do is that x has to take value 1 at all times and y can vary between 1 and 2. Does the above code make sense for this purpose? And is it different from:
if ( x == 1 && y == 1 || y == 2 ){
// do something
}
Yes, they do. What you're really asking is what is the operator precedence for && and ||?
&& has higher precedence than ||, which means it will be evaluated first if the order isn't specified explicitly using brackets (as you do in your first example).
You can think of precedence as the order in which PHP adds brackets to the expression if you haven't already put them in. In your second example, the operator with the highest precedence is ==, so all instances of these are grouped with brackets:
(x == 1) && (y == 1) || (y == 2)
The next highest is &&, so now we add brackets around these:
((x == 1) && (y == 1)) || (y == 2)
The expression is now unambiguous, so we needn't add any more brackets.
Hopefully it's clear from this argument that the first expression in your post is not the same as the second. For example, if x==0 and y==2, the first expression (correctly) evaluates to false, while the second evaluates to true.
See here for a list of operator precedences in PHP.
Yes,
in the first code,‍‍ ‍‍‍‍‍x == 1‍ will be checked first and the result will be checked against the result of y == 1 || y == 2 .
and in the second one , x == 1 && y == 1 will be checked at first and the result of it will be checked against || y == 2
&& has higher precedence than ||, so it'll be evaluated first. The use of parentheses helps you make sure the order of execution is same as what you expect.
From the PHP manual:
Use of parentheses, even when not strictly necessary, can often increase readability of the code by making grouping explicit rather than relying on the implicit operator precedence and associativity.
The && (logical AND) operator indicates whether both operands are true.
The || (logical OR) operator indicates at least one of the operands are true. And...what an operand is?
when you use a simple expression, like x == 1, that is considered an operand.
if you use brackets, everything inside the brackets is consider one operand, no matter how complex it is inside. So you can group conditions.
so x == 1 && ( y == 1 || y == 2 ) will evaluate if the first operand x == 1 is true, and the second operand, the whole ( y == 1 || y == 2 ) is true.
To know if something inside brackets is true or false, whatever it has inside is evaluated as an independent expression.
so, we have to operands. First, it will check if x == 1 is true. If it is false, it wont check what is inside the brackets, it doesnt matter since anyways the first condition is not fulfilled. if x==1, we can check the second operand:
so it will check the expresions inside the brackets, this is, y == 1 || y == 2, and if some is true, then ( y == 1 || y == 2 ) is true operand, and the whole expression will be x == 1 && true, so basicaly it now depends on x, and if none inside the brackets is true, then ( y == 1 || y == 2 ) is a false operand, and the whole operation will be x == 1 && false so everything is false
If you dont use brackets, you can achieve the same results, but you will have to check the precedence rules, that will be harder to keep in mind at the begining
I recommend that before you learn a programing language, you read a few tutorials about boolean algebra and logic. Everything will be easier after that.
in first example
the left side is evaluated first. if that is true it looks to the right side which is the bracket so it goes to the bracket and evaluates it and than checks against left side.
the second example will not work as you want because if x!=1 it will still go to right side to look for y==1 and you can end up with true.
Brackets don't make a difference. If you want to read more about it, look at the wikipedia page of Boolean logic:
http://en.wikipedia.org/wiki/Boolean_algebra

isset and != in the same if clause

In my script a particular array element (say, $foo['bar']) can take different values, or no value at all. A particular action is triggered if the value of $foo['bar'] is not equal to, say, 42. The following code
if (!isset($foo['bar']) || ($foo['bar'] != '42')) action()
is not ideal, because php issues a warning about when $foo['bar'] is not set.
Question: is there an elegant way to test for such condition?
This code:
if (!isset($foo['bar']) || $foo['bar'] != 42) {
}
Because of short-circuiting logic will actually not issue any warnings, because it skips at the first truthy condition, in this case that happens if $foo['bar'] is not defined.
This can also be seen from the opcodes that the compiler generates for your code:
compiled vars: !0 = $foo
line # * op fetch ext return operands
------------------------------------------------------------------------------
3 0 > ZEND_ISSET_ISEMPTY_DIM_OBJ 1 ~0 !0, 'bar'
1 BOOL_NOT ~1 ~0
2 > JMPNZ_EX ~1 ~1, ->6
3 > FETCH_DIM_R $2 !0, 'bar'
4 IS_NOT_EQUAL ~3 $2, 42
5 BOOL ~1 ~3
6 > > JMPZ ~1, ->8
4 7 > > JMP ->8
8 > > RETURN 1
The below opcode is important:
2 > JMPNZ_EX ~1 ~1, ->6
The inverted outcome of isset($foo['bar']) gets checked and if truthy the code jumps over the next few statements that actually inspect the value of $foo['bar'], thereby avoiding any notices.
This also means that if you would reverse the two operands of || you will get a notice and the second operand is mostly useless anyway.
Because values like 0, false, [], etc. are also not equal to 42 you can use empty() as well:
if (empty($foo['bar']) || $foo['bar'] != 42) {
}
This arguably makes the code easier to read.
Can be in this way
$bar = isset($foo['bar']) ? $foo['bar'] : NULL;
There you don't get warning and you are setting the variable.
Then you do the check
if($bar != 42 && !empty($bar)){
//do something
}
Read Ternary Operator
The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.
I think this is what you want:
if (!(isset($foo['bar']) && ($foo['bar'] = '42'))) action();
For PHP 5.3+ you can use optimitzed version of Emilio Gort answer:
$bar = isset($foo['bar']) ?: '';
if ($bar != 42) action();

Explain php if statement

Can someone please explain in detail what these if statements are doing?
What does the three === signs to in the first one, and What does the single & in the second mean?
$aProfile = getProfileInfo($iId);
if($aProfile === false)
return false;
if(!((int)$aProfile['Role'] & $iRole))
return false;
=== tests for type-safe equality.
'3' == 3 will return true, but '3' === 3 will not, because one's a string and one's an integer. Similarly, null == 0 will return true, but null === 0 will not; 10.00 == 10 will return true, but 10.00 === 10 will not.
& is the bitwise AND operator. It returns a bitmask in which a bit is set if both the corresponding bits are set from the original two bitmasks.
For example:
$x = 5;
$y = 17;
echo $x & $y;
causes 1 to be echoed. $x is ...000101, $y is ...010001. The only bit that is set in both of them is the rightmost one, so you get ...000001, which is 1.
Here's a good guide to PHP operators:
http://www.tuxradar.com/practicalphp/3/12/3
See the section on bitwise operators for info on the &.

C & PHP: Storing settings in an integer using bitwise operators?

I'm not familiar with bitwise operators, but I have seem them used to store simple settings before.
I need to pass several on/off options to a function, and I'd like to use a single integer for this. How can I go about setting and reading these options?
You sure can do it in PHP.
Let's say you have four booleans you want to store in a single value. That means we need four bits of storage space
0000
Each bit, when set individually, has a unique representation in decimal
0001 = 1 // or 2^0
0010 = 2 // or 2^1
0100 = 4 // or 2^2
1000 = 8 // or 2^3
A common way to implement this is with bit masks to represent each option. PHP's error levels are done this way, for example.
define( 'OPT_1', 1 );
define( 'OPT_2', 2 );
define( 'OPT_3', 4 );
define( 'OPT_4', 8 );
Then when you have an integer that represents 0 or more of these flags, you check with with the bitwise and operator which is &
$options = bindec( '0101' );
// can also be set like this
// $options = OPT_1 | OPT_3;
if ( $options & OPT_3 )
{
// option 3 is enabled
}
This operator works as such: only bits that are set in both operands are set in the result
0101 // our options
0100 // the value of OPT_3
----
0100 // The decimal integer 4 evaluates as "true" in an expression
If we checked it against OPT_2, then the result would look like this
0101 // our options
0010 // the value of OPT_2
----
0000 // The decimal integer 0 evaluates as "false" in an expression
It works pretty much the same way in both languages, a side by side comparison:
C:
#include <stdio.h>
#include <stdint.h>
#define FLAG_ONE 0x0001
#define FLAG_TWO 0x0002
#define FLAG_THREE 0x0004
#define FLAG_FOUR 0x0008
#define FLAG_ALL (FLAG_ONE|FLAG_TWO|FLAG_THREE|FLAG_FOUR)
void make_waffles(void)
{
printf("Yummy! We Love Waffles!!!\n");
}
void do_something(uint32_t flags)
{
if (flags & FLAG_TWO)
make_waffles();
}
int main(void)
{
uint32_t flags;
flags |= FLAG_ALL;
/* Lets make some waffles! */
do_something(flags);
return 0;
}
PHP:
<?php
define("FLAG_ONE", 0x0001);
define("FLAG_TWO", 0x0002);
define("FLAG_THREE", 0x0004);
define("FLAG_FOUR", 0x0008);
define("FLAG_ALL", FLAG_ONE|FLAG_TWO|FLAG_THREE|FLAG_FOUR);
function make_waffles()
{
echo 'Yummy! We Love Waffles!!!';
}
function do_something($flags)
{
if ($flags & FLAG_TWO)
make_waffles();
}
$flags |= FLAG_TWO;
do_something($flags);
?>
Note, you don't absolutely need to use constants, I just use them out of habit. Both examples will run, I compiled the C version via gcc -Wall flags.c -o flags. Change flags in either example to anything but FLAG_TWO or FLAG_ALL and (sadly) no waffles will be made.
In the C version, you don't have to tickle the preprocessor, it could quite easily be an enum, etc - that's an exercise for the reader.
quote
"the idea is not good, really. you would better pass few boolean. if you want use bitwise then
function someFunc($options)
{
if ($options & 1 != 0)
//then option 1 enabled
if ($options & (1 << 1) != 0)
//then option 2 enabled
if ($options & (1 << 2) != 0)
//then option 3 enabled
}
"
What you have done would be okay if you were checking for a single value, although not optimal, so checking that a bit is enabled, but lets say we wanted to be able to match any, or exact we could have the following methods
function matchExact($in, $match) { // meets your criterion, as would a switch, case, but ultimately not suited for use with flags
return $in === $match;
}
function matchAny($in, $match) { // meets original criterion with more lexical name however it returns true if any of the flags are true
return $in |= $match;
}
if you then wanted to expand upon this by having specific actions only happening if bit x,y,z was enabled then you could use the following
function matchHas($in, $match) { // more bitwise than === as allows you to conditionally branch upon specific bits being set
return $in &= $match;
}
I also think if you are doing what was done in the above quote, flags may not be the best idea, exact values might be better, which does have the benefit of allowing more discreet actions. (0-255) for 8-bit over 8 distinct flags
The whole reason flags work so well is because in base 2 "8" does not contain "4", and "2" does not contain "1".
________________________
|8|4|2|1|Base 10 Value |
------------------------
|1|1|1|1|15 |
|1|1|1|0|14 |
|1|1|0|1|13 |
|1|1|0|0|12 |
|1|0|1|1|11 |
|1|0|1|0|10 |
|1|0|0|1|9 |
|1|0|0|0|8 |
|0|1|1|1|7 |
|0|1|1|0|6 |
|0|1|0|1|5 |
|0|1|0|0|4 |
|0|0|1|1|3 |
|0|0|1|0|2 |
|0|0|0|1|1 |
|0|0|0|0|0 |
------------------------

What is the difference between the | and || operators?

| and || - what is the difference between these two operators in PHP?
| is a bitwise or, || is a boolean or.
Meaning
| is binary operator, it will binary OR the bits of both the lefthand and righthand values.
|| is a boolean operator, it will short circuit when it encounters 'true' (any non-zero value, this includes non-empty arrays).
Examples
print_r(1 | 2) // 3
print_r(1 || 2) // 1
When used with functions:
function numberOf($val) {
echo "$val, ";
return $val;
}
echo numberOf(1) | numberOf(2); // Will print 1, 2, 3
echo numberOf(1) || numberOf(2); // Will print 1, 1
Just like the & and && operator, the double Operator is a "short-circuit" operator.
For example:
if(condition1 || condition2 || condition3)
If condition1 is true, condition 2 and 3 will NOT be checked.
if(condition1 | condition2 | condition3)
This will check conditions 2 and 3, even if 1 is already true. As your conditions can be quite expensive functions, you can get a good
performance boost by using them.
There is one big caveat, NullReferences or similar problems. For example:
if(class != null && class.someVar < 20)
If class is null, the if-statement will stop after "class != null" is false. If you only use &, it will try to check class.someVar and you get a
nice NullReferenceException. With the Or-Operator that may not be that much of a trap as it's unlikely that you trigger something bad,
but it's something to keep in mind.
No one ever uses the single & or | operators though, unless you have a design where each condition is a function that HAS the be
executed. Sounds like a design smell, but sometimes (rarely) it's a clean way to do stuff. The & operator does "run these 3 functions,
and if one of them returns false, execute the else block", while the | does "only run the else block if none return false" - can be useful,
but as said, often it's a design smell.
| operates on the bits of a variable: 2 | 4 = 6
|| operates on The Boolean value of a variable: 2 || 4 = TRUE
| -> binary operator || -> Boolean operator or -> also a Boolean
operator with lower precedence
$x = false | true; //will set $x to an integer
$x = false || true; //will set $x to true
$x = false or true; //will set $x to false exactly the same that:
($x = false) || true;

Categories