Consider the following code:

```
$x = NULL;
if ('0xFF' == 255) {
$x = (int)'0xFF';
}
```

What will be the value of `$x`

after this code executes? Explain your answer.

Answer:

Perhaps surprisingly, the answer is neither NULL nor 255. Rather, the answer is that `$x`

will equal 0 (zero).

Why?

First, let’s consider whether `'0xFF' == 255`

will evaluate to true or false. When a hex string is loosely compared to an integer, it is converted to an integer. Internally, PHP uses `is_numeric_string`

to detect that the string contains a hex value and converts it to an integer (since the other operand is an integer). So in this case, ‘0xFF’ is converted to its integer equivalent which is 255. Since 255 = 255, this condition evaluates to true. (Note that this only works for hex strings, not for octal or binary strings.)

But if that’s the case, shouldn’t the statement `$x = (int)'0xFF';`

execute and result in `$x`

being set equal to 255?

Well, the statement does execute, but it results in `$x`

being set equal to 0, *not* 255 (i.e., it is *not* set to the integer equivalent of ‘0xFF’). The reason is that the explicit type cast of the string to an integer uses `convert_to_long`

(which works differently than the`is_numeric_string`

function that was used in evaluating the conditional expression, as explained above). `convert_to_long`

processes the string one character at a time from left to right and stops at the first non-numeric character that it reaches. In the case of ‘0xFF’, the first non-numeric character is ‘x’, so the only part of the string processed is the initial ‘0’. As a result, the value returned by `(int)'0xFF'`

is 0, so when the code completes, `$x`

will be equal to 0.