1

Hi...
I have a small doubt about php print statment. pls let me know if there is any reason
Here is a doubt for me.

<?php
$a=08;
print $a;
?>

why its output is 0.

4
Contributors
5
Replies
6
Views
7 Years
Discussion Span
Last Post by jeet_portal
0

Hey.

Because when you add a 0 to the start of an integer, PHP assumes you are using octal notation, in which the number 8 does not exist.

To print 8 in that way, you would have to do:

$a=010;
print $a;

See the manual for details.

1

Neither of those actually change anything, samarudge.

Your first example is exactly like the one the jeet_portal posted in the first post. Using print instead of echo makes absolutely no difference in this context.
Because you do $a=08; , the value of $a will always be 0. You start of with a 0, which makes PHP read it as an octal integer. And because you use 8 - which doesn't exist when using octal notation - it is truncated, leaving only the 0.

The second one will be printed as is. It's a string, and PHP has no reason to convert it before printing it. Not unless you give it a reason to, which you don't.

You could fix this, though, by having sprintf convert a string version of the number into a proper decimal number.

<?php
$a = (int)sprintf('%d', '08');
echo $a;
?>
0

Neither of those actually change anything, samarudge.

Your first example is exactly like the one the jeet_portal posted in the first post. Using print instead of echo makes absolutely no difference in this context.
Because you do $a=08; , the value of $a will always be 0. You start of with a 0, which makes PHP read it as an octal integer. And because you use 8 - which doesn't exist when using octal notation - it is truncated, leaving only the 0.

The second one will be printed as is. It's a string, and PHP has no reason to convert it before printing it. Not unless you give it a reason to, which you don't.

You could fix this, though, by having sprintf convert a string version of the number into a proper decimal number.

<?php
$a = (int)sprintf('%d', '08');
echo $a;
?>

Great info Atli... Guess i need to get back to basics.. never knew this stuff!!
really appreciate it..
keep rockin...

Edited by venkat0904: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.