Reputation: 1193
I have the following code:
$a = 012;
echo $a/4;
echo '<br>';
echo $a+4;
echo '<br>';
echo $a;
This generates the following output:
2.5
14
10
However, I expect:
3
16
12
Why does this happen when $a
starts with a 0?
Upvotes: 0
Views: 1045
Reputation: 1
For good answer please open link.
012
is octal number. In octal, numbers consist of 8 decimals. Start number with zero. skip remaining 2 digit left 12.
8^0 = 1,8^1=8 So 8+2=10
10/4 = 2.5 => $a+4 = 10 + 4 = 14;
Upvotes: 0
Reputation: 4399
The answer is down to the 0 in front defining the number as an octal (instead of a normal base 10 number). Note the page on Integers in the PHP Documentation:
<?php
$a = 1234; // decimal number
$a = -123; // a negative number
$a = 0123; // octal number (equivalent to 83 decimal)
$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)
$a = 0b11111111; // binary number (equivalent to 255 decimal)
?>
So basically an octal is where numbers go up to 7 in each column instead of 9. Therefore the 1 in the rightmost column makes the number an 8, the two in the leftmost column adds 2 on, therefore the number is 10.
In hexadecimal numbers defined in PHP by starting with 0x
they count to 15 (known as base 15); A representing 10, B representing 11,.. all the way up to F representing 15. Binary numbers (in PHP they are defined by starting with 0b
) on the other hand only go up to 1, they only have two values in each column 0 and 1.
You can use the octdec
function to get around this (converting the octal to a decimal):
<?php
$a = octdec(012);
echo $a/4;
echo '<br>';
echo $a+4;
echo '<br>';
echo $a;
?>
When the division happens, PHP does some type juggling and the octal is converted to an integer. Hence why you get the result you do.
Before PHP 7 invalid numbers in octals (like 8 or 9) were ignored, in PHP 7 they now cause an error.
Upvotes: 1
Reputation:
As already specified by @Rizier123 you must follow the integer type doc.
As specified in the official documentation of integers type http://php.net/manual/en/language.types.integer.php
Integers can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation, optionally preceded by a sign (- or +)
$n = 123; // decimal number
$n = -123; // negative number
$n = 0234; // octal number
...
So in your case the first number $a = 012
means that it's in octal notation.
When you do the division: $a/4
PHP proceed with type juggling converting it to decimal base and dividing by 4
$a = 012; // 10 in decimal base
echo $a/4; // 10/4 -> 2.5
Note: Prior to PHP 7, if an invalid digit was given in an octal integer (i.e. 8 or 9), the rest of the number was ignored
Upvotes: 1