sadq3377 - 10 months ago 42

PHP Question

I ran across this example in the PHP documentation:

`<?php`

$tests = array(

"42",

1337,

0x539,

02471,

0b10100111001,

1337e0,

"not numeric",

array(),

9.1

);

foreach ($tests as $element) {

if (is_numeric($element)) {

echo "'{$element}' is numeric", PHP_EOL;

} else {

echo "'{$element}' is NOT numeric", PHP_EOL;

}

}

?>

Output:

`'42' is numeric`

'1337' is numeric

'1337' is numeric

'1337' is numeric

'1337' is numeric

'1337' is numeric

'not numeric' is NOT numeric

'Array' is NOT numeric

'9.1' is numeric

The five examples after '42' all evaluate to '1337'. I can understand why this is the case for '1337e0' (scientific notation), but I don't understand why that is the case for the rest of them.

I wasn't able to find anyone mentioning it in the comments of the documentation and I haven't found it asked here, so could anyone explain why '0x539', '02471', and '0b10100111001' all evaluate to '1337'.

Answer

When outputting all numbers get converted to normal representation. Which is decimal number system, and non-scientific notation (e.g. `1e10`

- scientific float).

Hex:

*Hex numbers start with 0x and are followed by any of 0-9a-f.*

```
0x539 = 9*16^0 + 3*16^1 + 5*16^2 = 1337
```

Octal:

*Octal numbers start with a 0 and contain only the integers 0-7.*

```
02471 = 1*8^0 + 7*8^1 + 4*8^2 + 2*8^3 = 1337
```

Binary:

*Binary numbers start 0b and contain 0s and/or 1s.*

```
0b10100111001 = 1*2^0 + 1*2^3 + 1*2^4 + 1*2^5 + 1*2^8 + 1*2^10 = 1337
```

Source (Stackoverflow)