> > |
%META:TOPICINFO{author="RickArchibald" date="1097416800" format="1.0" version="1.1"}%
Exercises in PHP
- Embed his snippet in a page
- Run it
- Report the results
If possible, repeat on a different machine.
giorgio dot balestrieri at mail dot wind dot it
09-Mar-2004 09:49
For number formatting (like writing numbers with leading zeroes etc.) , sprintf is much faster than str_pad.
Consider the following snippet (it take some minutes to run):
<?
echo "str_pad test started, please wait...\n";
$intStart = time();
for ($idx = 1; $idx <= 10000000; $idx++)
$strFoo = str_pad($idx, 10, "0", STR_PAD_LEFT);
$intEnd = time();
echo "str_pad cycle completed in " . ($intEnd - $intStart) . " seconds\n";
echo "sprintf test started, please wait...\n";
$intStart = time();
for ($idx = 1; $idx <= 10000000; $idx++)
$strFoo = sprintf("%010d", $idx);
$intEnd = time();
echo "sprintf cycle completed in " . ($intEnd - $intStart) . " seconds\n";
?>
The str_pad cyle runs 80-100% slower on my pc...
anon at example dot com
30-May-2003 11:50
alternatively use substr_replace to zero pad:
$new_id = substr_replace("00000", $id, -1 * strlen($id));
Annotate (add beginner level comments to) the function he defines.
tacomage at NOSPAM dot devilishly-deviant dot net
07-Jul-2004 09:04
If you want to pad a string to a certain screen length with &nbsp; or other HTML entities, but don't want to risk messing up any HTML characters inside the string, try this:
<?
function str_pad_as_single($input, $len, $pad, $flag=STR_PAD_RIGHT)
{
$trans=array('$'=>$input,' '=>$pad);
$output=str_pad('$',$len-strlen($input)+1,' ',$flag);
$output=strtr($output,$trans);
return $output;
}
echo str_pad_as_single('<img src="some.gif">',22,' ');
// will output <img src="some.gif">
echo str_pad_as_single('<img src="some.gif">',22,' ',STR_PAD_BOTH);
// will output <img src="some.gif">
echo str_pad_as_single('<img src="some.gif">',22,' ',STR_PAD_LEFT);
// will output <img src="some.gif">
?>
It works by using single characters for str_pad, then replacing the characters with the full strings using strtr, so the two strings can't interfere with each other. It also conveniently has the same syntax as str_pad. Yes, I realize that spacing an image with text isn't the best idea, but it's just an example, it'll apply to other HTML as well :-P
-- Main.RickArchibald - 10 Oct 2004 |