1

Why does this code only print zero? Why does it not print the value of a?

<?php
$a=099;
echo $a;
?>
Don't Panic
  • 41,125
  • 10
  • 61
  • 80
  • 2
    Not valid octal – Ultimater Dec 22 '16 at 17:19
  • 1
    echo is meant to print a `string` and your `$a` is an integer, try this instead - `$a='099'; echo $a;` – Saumya Rastogi Dec 22 '16 at 17:19
  • 1
    it did exactly what you asked it to do. if you want to output as a string you would need to set `$a='099';` – happymacarts Dec 22 '16 at 17:20
  • 1
    @SaumyaRastogi echo can print integers. They're automatically converted to strings in that context. I think the issue here is just that the OP did not realize what the leading zero was doing. – Don't Panic Dec 22 '16 at 17:28
  • If you're wondering what the point of octal is, [this SO question](http://stackoverflow.com/questions/2609426/in-what-situations-is-octal-base-used) has some good answers about that, although there are also some silly ones there. [Here is a better one on Software Engineering.](http://softwareengineering.stackexchange.com/questions/98692/where-are-octals-useful) – Don't Panic Dec 22 '16 at 17:41

2 Answers2

4

As Ultimater points out, you have assigned $a to an invalid octal number.

A numeric value (known as an "integer literal" in this case) prefaced with a zero is assumed by the parser to be an octal (base 8) number. As your number contains nines, which are not in the base (base 8 digits are 0-7), it's not valid and the parser evaluates it to zero.

For example, this does work:

$a = 077;
echo $a;  //63

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

Kevin_Kinsey
  • 2,285
  • 1
  • 22
  • 23
1

The number started with '0' is Octal number. But Octor number has 0~7, has no 8, 9. so $a is set zero. If you want to print '099', try

$a = '099'; 
echo $a;   //print 099 

If you want to get number, try

$a = 045; 
echo $a;    //print 37(Decimal number)
anwerj
  • 2,386
  • 2
  • 17
  • 36
Star_Man
  • 1,091
  • 1
  • 13
  • 30