Integer with 0 to the left is printed as another number

Asked

Viewed 3,280 times

17

I have this code:

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

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

641980

Why does that happen?

  • 4

    Supplementary reading: http://answall.com/questions/25031/

4 answers

15


Numbers started with zero, since valid, are interpreted based on 8 (octal), ie, 02345674 was interpreted on the basis of 8 and its representation on the basis of 10 is 641980.

The warning manual on this on the page about integers

That one website does base 8 x base 10 conversions

  • 1

    @Miguel Just start from scratch.

11

As told by @Lost O php manual mentions this behavior

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

So the best way to print the value of integers that have 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 remains integer, as you can see in the article Conversion of data types in PHP.

  • Very obnoxious, I get it

5

You can get the same result without converting your values array for string, if using the function sprintf to save the formatted value you want to get.

In this case, the option '%o' of the function causes "The argument to be treated as an integer, and shown as an octal number" (Excerpt from PHP Handbook).

If you want to get the zeros, you will have to use '%08o'. This will return the value filled with zeros to the left if there is less 8 numbers in their entirety.

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

4

You can work with these numbers as string.

Just add quotes:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.