Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this PHP syntax with a caret called and what does it do?

I came across this syntax in a codebase and I can't find any more info on it. It looks like the caret operator (XOR operator), but because the statement below was executed when a certain condition was met I don't think that is it.

$this->m_flags ^= $flag;

Because I don't know what it's called I also can't search for it properly..

Update: Because of Cletus' answer: Are the following lines then functionally equal?

$a = $a ^ $b; 
$a ^= $b; // the shorthand for the line above
like image 635
Niels Bom Avatar asked Aug 11 '11 15:08

Niels Bom


People also ask

What is the caret symbol used for?

Carets are used in proofreading to signal where additional words or punctuation marks should be added to a line of text.

What is the caret symbol called?

Alternatively referred to as the circumflex, the caret is the symbol ( ^ ) above the 6 key on a standard United States qwerty keyboard. In mathematics, the caret represents an exponent, such as a square, cube, or another exponential power.

What is the caret operator?

The caret is used in various programming languages to signify the XOR operator, control characters and string concatenation. It is still used in regular expressions, to mark the beginning of a line or string. Pascal makes use of caret for pointer declarations.

What does -> represent in PHP?

The object operator, -> , is used in object scope to access methods and properties of an object. It's meaning is to say that what is on the right of the operator is a member of the object instantiated into the variable on the left side of the operator. Instantiated is the key term here.


2 Answers

It's bitwise XOR equals. It basically toggles a flag because I'm getting $flag is a power-of-2. To give you an example:

$a = 5; // binary 0101
$b = 4; // binary 0100
$a ^= $b; // now 1, binary 0001

So the third bit has been flipped. Again:

$a ^= $b; // now 5, binary 0101
like image 184
cletus Avatar answered Nov 13 '22 09:11

cletus


Bitwise XOR and assign operator http://php.net/manual/en/language.operators.bitwise.php

like image 31
steveo225 Avatar answered Nov 13 '22 11:11

steveo225