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

Refer A Friend using Revolution Money Exchange
Uniform ID PDF Print E-mail
Written by Handy PHP Administrator   
Sunday, 03 September 2006 15:16
Description:
  string uniform_id (string number, int places[, string prefix[, string suffix]])  
     
  This is handy for creating new filenames from either a counter file or record id.   It converts the numeric count or id to a uniform leading zero number then adds any kind of prefix and suffix that you want.
     
Function:
  function uniform_id($value, $places, $prefix='', $suffix=''){
// 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 = $prefix . $leading . $value . $suffix;
    }
    else{
       $output = $prefix . $value . $suffix;
    }
    return $output;
}
   
 
Usage:
  echo uniform_id('654321', 10, 'photo', '.gif');
     
Result:
  photo0000654321.gif
     
Notes:
 

 

You must use either single or double quotes in the first, third, and forth arguments 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 and 10 is the total number of digits including all of the zeros and numbers in the value.   photo is your prefix and .gif is your suffix.

prefix and suffix are optional and can be left out of the call.   If you want to use suffix , something MUST be defined for prefix even if it is just ''.   prefix can be used without suffix .

Acceptable uniform_id calls:

uniform_id('654321', 10, '', '.gif') would output 0000654321.gif

uniform_id('654321', 10, 'file') would output file0000654321

uniform_id('654321', 10) would output 0000654321


In 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_sb_discuss:3}
Last Updated on Monday, 18 September 2006 01:18
 
Wordtracker Keyword Research
Earn More with LinkConnector