tags:

views:

186

answers:

6

Hay how can I convert

01 to 1
02 to 2

all the way to 9?

Thanks

+12  A: 

I assume the input is a string?

$str = "01";
$anInt = intval($str);

You may think that the leading 0 would mean this is interpreted as octal, as in many other languages/APIs. However the second argument to intval is a base. The default value for this is 10. This means 09->9. See the first comment at the intval page, which states that the base deduction you might expect only happens if you pass 0 in as the base.

Doug T.
If input is treated as an int, it will be handled as octal. (so 09->0)
erenon
@erenon, see my update.
Doug T.
A: 
$str = "05";
$last = $str[1];
Fortega
the intval() solution is more reliable in this case, as it can catch "009" as well.
Pekka
true. But my solution is faster, and the TS didn't say anything about the 009 :-)
Fortega
+1  A: 
$old_nums = array("01","02","03");

foreach($old_nums as $k => $v) {

ltrim($v,"0");

}
David Thomas
that's overkill
Gregory Pakosz
That depends entirely on where the numbers are coming from, and how they're stored, doesn't it? In this instance I offered this only as an alternative to Doug T.'s -already submitted and clearly accurate and efficient- answer.
David Thomas
A: 
$i = substr($input, 1, 1);
erenon
+1  A: 
$x="01";
$x=+$x;

$x="02";
$x=+$x;

...

or

$x=+"01";

should work for both int, and string

S.Mark
A: 

If you want to use the generic regular expression solution: 's/[0]([0-9])/\1/' (add in anchors as appropriate)

Vitali