Re: Why $a +1 is not 02 ??

From: Date: Wed, 24 Nov 2004 03:28:08 +0000
Subject: Re: Why $a +1 is not 02 ??
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-202741@lists.php.net to get a copy of this message
Labunski wrote:
Hello, I have small problem.. $a = 01; echo $a+1; //this will display 2, instead of 02. How to get 02? thanks. Lab.
You need to understand how PHP treats integers. It can never start an integer with a zero unless it's an octal or a hexadecimal number. And PHP will not hesitate to parse a string as an integer. For example, even if you had $a = "01" (clearly "01" is a string), and then did echo $a+1, you would still get 2 since "01" will evaluate to the integer 1. Read more on integers here: http://www.php.net/types.integer Now, to answer your question, just use the str_pad() function: http://www.php.net/str_pad Looks like this: $a = 1; echo str_pad($a+1, 2, "0", STR_PAD_LEFT); This will output "02" as desired. -- Ben Ramsey Zend Certified Engineer http://benramsey.com --------------------------------------------------- Atlanta PHP - http://www.atlphp.org/ The Southeast's premier PHP community. ---------------------------------------------------

« previous php.general (#202741) next »