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.
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.
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);
}
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
)
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
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()