Integer with 0 on the left is printed as another number

16

I have this code:

$mob_numbers= array(02345674, 12345675, 22345676, 32345677);
echo ($mob_numbers[0]);

I wanted to print the first element of array but the output of that is:

  

641980

Why does this happen?

    
asked by anonymous 14.03.2014 / 13:17

4 answers

14

Numbers starting with zero, as long as they are valid, are interpreted with base 8 (octal), that is, 02345674 was interpreted with base 8 and its representation in base 10 is 641980 .

The manual alerts you on the integers page

This site does conversions between base 8 X base 10

    
14.03.2014 / 13:21
10

As said by @ lost The php manual > mentions this behavior

  

$ a = 0123; // octal number (equivalent to 83 in decimal)

So the best way to print the value of integers that have a 0 on the left is:

$mob_numbers = array("02345674", "12345675", "22345676", "32345677");
echo (int)$mob_numbers[0];    //Retorno 2345674

(int) converts the string to integer, this ensures that the number stays as an integer, as you can see in the article #

    
14.03.2014 / 14:06
5

You can achieve the same result without converting the values from your array to string , if you use the sprintf to save the formatted value you want to get.

In this case, the option '%o' of the function causes "The argument is treated as an integer, and shown as an octal number" (excerpt taken from the PHP Manual).

If you want to get the zeros, you have to use '%08o' . This will return the value filled with leading zeros if there are less than 8 numbers in its integer.

Example:

    $mob_numbers= array(02345674, 12345675, 22345676, 32345677);

    echo sprintf('%08o', $mob_numbers[0]); // preenche com zero quando não há 8 números

    echo sprintf('%o', $mob_numbers[0]); // formata o valor sem o zero
    
20.03.2014 / 04:30
4

You can work with these numbers as string .

Just add quotes:

$mob_numbers= array("02345674", "12345675", "22345676", "32345677");
echo ($mob_numbers[0]);
    
14.03.2014 / 13:32