|
PHP Resources -
Handy PHP Functions
|
|
Written by M. L. Griswold
|
|
Sunday, 03 September 2006 |
|
|
Description:
|
|
|
stringleading_zeros(string number, int places)
|
|
|
|
|
|
|
This function is handy if you need to add leading zeros to a number for various reason. The most obvious reason to add leading zeros would be to create numberic or alph-numeric file names that you want to ensure are sorted correctly.
|
|
|
|
|
|
Function:
|
|
|
function leading_zeros($value, $places){ // Function written by Marcus L. Griswold (vujsa)
// Can be found at http://www.handyphp.com // Do not remove this header!
if(is_numeric($value)){ for($x = 1; $x <= $places; $x++){
$ceiling = pow(10, $x);
if($value < $ceiling){
$zeros = $places - $x;
for($y = 1; $y <= $zeros; $y++){
$leading .= "0";
}
$x = $places + 1;
}
}
$output = $leading . $value;
}
else{
$output = $value;
} return $output;
}
|
|
|
|
|
|
Usage:
|
|
|
echo leading_zeros('654321', 10);
|
|
|
|
|
Result:
|
|
|
0000654321
|
|
|
|
|
Notes:
|
|
|
You must use either single or double quotes in the first argument of the function call. Failure to do so will result in an undesirable number format. If your output is displayed in an exponential format, you probably left out your quotes. Additionally, any variable used in the first argument must contain a string and not a number.
For example,
$value = 1234567890987654321;
Doesn't work but,
$value = '1234567890987654321';
Does work!
In the example above,'654321' is the number which you want to format and10 is the total number of digits including all of the zeros and numbers in the value.
I most cases the PHP function str_pad will work as well or better and is more efficient. Additionally, str_pad doesn't care if the value is numeric or not.
|
Discuss this article on the forums. (3 posts)
|
|
Last Updated ( Thursday, 07 September 2006 )
|