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.

user783322
  • 479
  • 1
  • 8
  • 19

4 Answers4

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);
}
xdazz
  • 158,678
  • 38
  • 247
  • 274
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
)
Bryan Geraghty
  • 586
  • 4
  • 11
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

Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192
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()