You are here: Re: A puzzle about leading zeros « PHP Programming Language « IT news, forums, messages
Re: A puzzle about leading zeros

Posted by Bob Stearns on 08/12/05 06:09

TheTeapot wrote:

> Hi all,
>
> Here's a puzzle:
> // Say I have an array of numbers set up like so:
> $arr = array(15,16,17,100,121,1000);
>
> // How can I create a function so that I can use it like so:
> addleadingzeros_arr($arr);
>
> // and have the output look like:
> // array("0015","0016","0017","0100","0121","1000");
>
> Or, if the function only does one value like shown, so I can loop the
> array through, modifying each seperately.
> addleadingzeros_int(32);
> // Outputs: "0032"
>
> I'd prefer the first one though.
>
> Thanks,
> TheTeapot
>


function addleadingzeros_arr($arr) {
$res = array();
foreach($arr as $x)
if(abs($x)>$maxx) $maxx = abs($x);
mult = 1;
len = 0;
while(mult<maxx) {
mult *= 10;
len += 1;
}
foreach($arr as $k => $x)
$res[$k] = $x<0?"-":"" . right(mult+abs(x),len);

return $res;
}

Will do the trick without all the overhead of sprintf. If you know how
many leading zeroes you want, the first two loops can be omitted and the
correct values (10000 and 4 for instance, in your specified case). The
conditional and the abs can be omitted if you'll always have non
negative numbers in $arr. The code can be simplified if $arr is
subscripted by 0-n.

Untested, off the top of my head. Try before committing real data. YMMV.

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация