Why does $ variable = 0759 return 61?

I do not know how to do this, so I ask him here. Why does this happen when I declare the variable $something = 0759 , that it turns into 61. I know that the answer should be very simple, so please forgive my stupidity.

+7
variables php
source share
5 answers

This is an integer literal, you declare an octal number with a leading zero.

 $something = 0759; // octal 

The octal number system is the system with number 8. You can only use numbers between 0-7 (other numbers are discarded).

 $a = 0759; $b = 075; var_dump($a==$b); // bool(true) 

http://www.php.net/manual/en/language.types.integer.php

You can skip zeros with ltrim.

  $a = ltrim("0759", 0); echo $a; // 759 // and reformat as suggested with str_pad or printf echo str_pad($a, 4, "0", STR_PAD_LEFT); 
+14
source share

Why is this happening

In PHP (and most programming languages), numbers preceding 0 are treated as octal numbers . This is the base system number 8 and has numbers from 1 to 7.

Octal 0759 is equivalent to octal 075 (9 is discarded because there is no 9 in octal). Octal 075 is equivalent to decimal 61. PHP actually saves the number as octal, but when you exit with print / echo it is always in decimal, so 075 becomes 61.

Conversion

See Wikipedia on Eighth to Decimal Conversion. But this should give you a basic idea:

(075) 8 = (0 x 8 ^ 2) + (7 x 8 ^ 1) + (5 x 8 ^ 0)
(075) 8 = 0 + 56 + 5
(075) 8 = 61

Basically:

 7 * 8 = 56 5 * 1 = 5 ==== 61 

How to solve this problem

Just save the numbers as integers / strings and format them in the output.

Using sprintf() :

 echo sprintf('%04d', $number); // 0759 

Using str_pad() :

 echo str_pad($number, 4, '0', STR_PAD_LEFT); // 0759 

If you really want to keep the leading zero, save it as a string:

 $number = '0759'; 
+9
source share

Numbers starting with 0 can be thought of as an octal number notation by the PHP compiler.

Here you can find more detailed information: Use numbers starting with 0 in a variable in php

+2
source share

When you assign a number to avariable starting at 0, it is assumed to be octal, in your case (0759) 9 is not an octal digit, so ignored, 75 octal to decimal is 61.

+1
source share

a number starting with 0 is octal, but in octal you can use 0-7 rather than 9, so 0759 will be dropped to 075 and 075 in octal column 61 in decimal format

+1
source share

All Articles