Jump to content

Number with zero

- - - - -

  • Please log in to reply
4 replies to this topic

#1
lol33d

lol33d

    Programmer

  • Members
  • PipPipPipPip
  • 149 posts
Hi guys

i want change my number
my number is:
1
2
3
.
.
.
30

and i want change to:
01
02
03
.
.
.
30

all numbers in array.

help me please.

thank you

#2
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,124 posts
  • Location:Vancouver, Eh! Cleverness: 200
An example method:

$range = range(1, 30); //create sample array of 1 .. 30
$rangecount = count($range)
for($i = 0; $i < $rangecount; $i++) {
  //pad two width, to the left, with the string '0'
  $range[$i] = str_pad($range[$i], 2, '0', STR_PAD_LEFT); 
}

print_r($range);
I've not tested this specific code, although it is correct use. You must be aware that 04 could be considered an octal or the leading zero stripped off, and must be represented as a string "04" and so the array will be strings. You can convert them to integers as needed.

Edited by Alexander, 21 April 2011 - 03:01 PM.
. --> ,

Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#3
__ak

__ak

    Newbie

  • Members
  • PipPip
  • 24 posts
Wouldn't

$new = sprintf("%02d",$old);

work as well? Instead of string_pad?

#4
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,124 posts
  • Location:Vancouver, Eh! Cleverness: 200
The sprintf specifier you had supplied is not designed to work with integers, which would rely on the integer being converted to a string which is usually untrue for other languages that use sprintf. It is more simple to rely on a native function to PHP of which is designed to handle string padding rather than "integer padding".
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#5
__ak

__ak

    Newbie

  • Members
  • PipPip
  • 24 posts
Thanks once again!

Edited by __ak, 25 April 2011 - 04:05 AM.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users