435,165 Members | 894 Online
Need help? Post your question and get tips & solutions from a community of 435,165 IT Pros & Developers. It's quick & easy.

 P: n/a 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 Aug 11 '05 #1
8 Replies

 P: n/a On 11 Aug 2005 00:21:52 -0700, TheTeapot wrote: \$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"); http://php.net/sprintf http://php.net/foreach function f( \$a ) { \$b = array(); foreach ( \$a as \$v ) \$b[] = sprintf( '%04d', \$v ); return \$b; } Or using http://php.net/array-map function f( \$i ) { return sprintf( '%04d', \$i ); } \$b = array_map( 'f', \$a ); Or your own implementation of sprintf using http://php.net/substr \$padded = substr( '000'.\$int, -4 ); -- E. Dronkert Aug 11 '05 #2

 P: n/a TheTeapot schrieb: 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); You can create every function ;-) function addleadingzeros_arr(\$arr) { } // and have the output look like: output? you're talking of the return value ... // array("0015","0016","0017","0100","0121","1000"); loop through \$arr; eg. foreach(\$arr as \$value) { use sprintf } 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" sprintf is what you ar looking for I'd prefer the first one though. Hope it help Jo Aug 11 '05 #3

 P: n/a TheTeapot wrote: \$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"); \$arr = array(15,16,17,100,121,1000); addleadingzeros_arr(\$arr); function addleadingzeros_arr(&\$arr) { foreach (\$arr as &\$val) \$val=substr("000\$val",-4); } Csaba Gabor from Vienna Aug 11 '05 #4