Home » Php » php – Why does \$variable = 0759 give out 61?

# php – Why does \$variable = 0759 give out 61?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I don’t know how to google this one out so I an asking it here. Why does it happen that when I declare a variable `\$something = 0759` that it turns into 61. I know the answer must be very simple so please forgive my sillyness.

How to&Answers:

It is an Integer literal, you declare a octal number with a leading zero.

``````\$something = 0759; // octal
``````

The octal numeral system is a base-8 number system.
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 could skip the 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);
``````

## Why does it happen

In PHP (and most programming languages), numbers preceding with a `0` is treated as an octal number. It’s a base-8 number system and has digits from 1-7.

Octal 0759 is equivalent to octal 075 (9 is discarded because there’s no 9 in the octal system). Octal 075 is equivalent to decimal 61. PHP actually stores the number as octal, but when output with `print` / `echo` it’s always in decimal, so 075 becomes 61.

## The Conversion

See Wikipedia on Octal 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 resolve this issue

Simply store the numbers as integers / strings and format them on 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 preserve the leading zero, then store it as a string:

``````\$number = '0759';
``````

### Answer：

Numbers starting with 0 can be treated as octal number notation by the PHP compiler.

You can find more details here:
Use numbers starting with 0 in a variable in php

### Answer：

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

### Answer：

number starting with 0 is octal but in octal you can use 0-7 not 9 so 0759 will cast to 075 and 075 in octal is 61 in decimal