Handy PHP
TalkPHP
Get friendly help with your PHP problems for free.
www.talkphp.com
The PHP Resource Index

Refer A Friend using Revolution Money Exchange
Wordtracker Keyword Research
Leading Zeros PDF Print E-mail
Written by Handy PHP Administrator   
Sunday, 03 September 2006 15:13
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.



{mos_fb_discuss:3}
Last Updated on Friday, 08 September 2006 00:25
 
Capture media attention