Niels Bom
Niels Bom

Reputation: 9417

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

Upvotes: 9

Views: 10975

Answers (2)

cletus
cletus

Reputation: 625447

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

Upvotes: 18

steveo225
steveo225

Reputation: 11892

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

Upvotes: 3

Related Questions