2

I want to format my array vars to that numbers under ten have leading zeros, so:

$myArray=array(1,2,3,10,11,100);

So that it is:

$myArray=array(01,02,03,10,11,100);

Is there an easy function for this?

Thanks in advance.

5
  • 7
    Don't do this. Add the leading zero at output time instead
    – Pekka
    Mar 16, 2012 at 11:49
  • Okay, one way I've thought of is if(strlen($var)==1)$var="0".$var; but is there a better way?
    – user783322
    Mar 16, 2012 at 11:51
  • String is fine - it's actually for time "01:59:59", so I'll be strtotime anyway.
    – user783322
    Mar 16, 2012 at 11:52
  • 1
    If you're ultimately passing the values through strtotime(), why add the zero beforehand?
    – JJJ
    Mar 16, 2012 at 11:53
  • Why use strtotime if you have DateTime::createFromFormat.
    – N.B.
    Mar 16, 2012 at 11:57

4 Answers 4

5

In php, a leading zero means the number is a octal number.

You should just format it at the output time like:

$myArray=array(1,2,3,10,11,100);
foreach ($myArray as $var) {
  echo sprintf("%02d\n", $var);
}
5

This allows you to pad all values to a variable length.

Keep in mind a leading zero is not a valid integer representation. For portability reasons, If you want to store the values, the values should be converted to strings.

$myArray = array(1,2,3,10,11,100);
$pad_length = 2;

foreach ($myArray as &$item)
{
    $item = str_pad($item, $pad_length, '0', STR_PAD_LEFT);
}

print_r($myArray);

Outputs:

Array
(   
    [0] => 01
    [1] => 02
    [2] => 03
    [3] => 10
    [4] => 11
    [5] => 100
)
4

It's muche better to add the 0 when you print it otherwise you transform them to string:

$myArray=array(1,2,3,10,11,100);

foreach ($myArray as $number){
    printf("%02d\n", $number);
}

codepad here http://codepad.org/a3Bl4TeA

0
0

I have prefer to make my own scalable function to any other length you would like to use. here for example

function format3($number){
   if($number>99){$number=$number;}
     else{ if($number>9){$number="0".$number;} 
      else{$number="00".$number;
         }
     }
  return $number;
} 

just call format3(/your value/) to see your value displaid in three digit $value=3 echo format3($value) //display 003 You can extend the function for longest patterns formatX()

Not the answer you're looking for? Browse other questions tagged or ask your own question.