1

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

2 Answers 2

8

=== 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.

Sign up to request clarification or add additional context in comments.

3 Comments

And my favorite along those lines: 1.0 === 4/4 is false... 1 === 4/4 is true... (Of course, 1.0 == 4/4 is true)... (The reason it's my favorite, is 1.5 === 6/4 is true. So division sometimes returns a float, other times an int...)
@ircmaxell: Looks peculiar but it's nothing unique to PHP nor does it have anything to really do with PHP implementation. It's simply the PHP === being able to expose the underlying storage mechanisms. The result of 4/4 doesn't require floating point storage so it isn't used.
@webbiedave: Oh I know. But it's definitely not something that I expect to happen (I would assume that division always returns a float). I'm not saying that there's anything "wrong", just something to watch out for because it can be confusing at first (if you use === or type checks (is_float)...
3

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 &.

2 Comments

Nice link! The === (identical) operator is used very rarely in comparison to == (equality), but it can be useful on occasion. To make sure you are clear, two variables are only identical if they hold the same value and if they are the same type.
Thanks, Jeff. It should be noted, however, that the === operator really does what beginners expect == to do (it checks for equality of identity and type...so 1 === true is false whereas 1 == true is true). It's important for a beginner to give a good look at all the possible truth statements before using the == operator with any frequency...otherwise they may run into problems that aren't immediately simple to solve.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.