View Full Version : Explain this syntax
JasonDFR
01-18-2009, 10:09 PM
I came across this website and plan on going through it, but I got distracted by the line below. It works and evaluates to true.
I don't understand what is going on inside the if. Specificly the '&'.
Can one of you guys explain please? Thanks.
http://www.nyphp.org/content/presentations/GDintro/gd2.php
if (imagetypes() & IMG_GIF) echo "GIF Support is enabled<br />";
The result of imagetypes (http://www.php.net/imagetypes)() is a bitset (http://en.wikipedia.org/wiki/Bitset), and & is the bitwise operator (http://www.php.net/language.operators.bitwise) AND (http://en.wikipedia.org/wiki/Bitwise_operation#AND). The condition is expressing 'if the imagetypes() bitset has the IMG_GIF bit set', relying on PHP's interpretation of 0 as false.
For example, if we (probably inaccurately; it doesn't matter for the purposes of demonstration) let IMG_PNG = 1, IMG_GIF = 2, IMG_JPEG = 4, then 7 (1 + 2 + 4) expresses all three:
$imagetypes = 1 + 2 + 4;
// 1bin + 10bin + 100bin = 111bin = 7dec
$imagetypes & IMG_GIF;
// 111
// & 010
// = 010
$imagetypes = 1 + 4;
// remove GIF support
// 1bin + 100bin = 101bin = 5dec
// we could also express this as $imagetypes -= 2
// or $imagetypes ^= 2 (^ is XOR (http://en.wikipedia.org/wiki/Bitwise_operation#XOR))
// where the operands are composed only of powers of two,
// OR is equivalent to +, and XOR to -, but with a lower
// bound of 0.
$imagetypes & IMG_GIF;
// 101
// & 010
// = 000
JasonDFR
01-19-2009, 08:11 AM
Thanks Twey.
So would it be correct to say that the imagetypes() function returns a bitset and the & is checking that the IMG_GIF is represented in the bitset?
If imagetypes() evalutes to true AND IMG_GIF is in the result of calling imagetypes(), the if will be true?
I have never seen that syntax before. Are there any common uses for it?
If imagetypes() doesn't evaluate to true then it's 0, and 0 & x === 0 for all x. The return value of imagetypes() is not checked directly: don't confuse & (bitwise AND) with && (boolean AND). & is a mathematical operator like + or *, not a logical operator like &&, and it does not exhibit short-circuit behaviour.
If you were to program at a lower level, you'd see bit manipulation an awful lot. At this level, about all it's useful for is bitsets and performance tricks.
JasonDFR
01-19-2009, 10:08 AM
Makes perfect sense now Twey. Thanks a lot.
Powered by vBulletin® Version 4.2.2 Copyright © 2021 vBulletin Solutions, Inc. All rights reserved.