473,396 Members | 1,921 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

A puzzle about leading zeros

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 2724
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
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
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
"TheTeapot" <pe********@gmail.com> kirjoitti
viestissä:11*********************@g44g2000cwa.goog legroups.com...
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.


Some other examples were already mentioned, but I'll throw in just one more,
str_pad(). It padds the given string to given length and fills the empty
space with given string. A function using str_pad would be:

zero_fill($array, $length=4, $fill='0') {
$zf_arr = is_array($array) ? $array : array($array);
foreach($zf_arr as $key => $val)
$$zf_ret[$key] = str_pad($val, $length, $fill, STR_PAD_LEFT);
return is_array($array) ? $zf_ret : $zf_ret[0];
}

var_dump( zero_fill(32) ); // It can convert both single parameters...
var_dump( zero_fill(array(15,16,17,100,121,1000)) ); // or entire arrays.
var_dump( zero_fill(15023, 8) ); // you can also modify the length of the
output.
var_dump( zero_fill(23, 4, '-') ); // or the fill character.

I could not test it as I have no access to my usual testing server at the
moment, so I can't say if it works or not, but that's basicly something you
could use.

--
SETI @ Home - Donate your cpu's idle time to science.
Further reading at <http://setiweb.ssl.berkeley.edu/>
Kimmo Laine <et****************@5P4Mgmail.com>
Aug 11 '05 #5
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.
Aug 12 '05 #6
Thanks all, problem solved, used a variation on Ewoud Dronkert's
suggestion.

Thanks for the help,
TheTeapot

Aug 12 '05 #7
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


One thing to think about. "0121" as an integer is equivalent to 81. Numbers
with leading zeros are octal.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Aug 22 '05 #8
Not if you just append two zeros in "string" form to them.

So what you need to do in your function is:

1) Count how many characters the number is.
2) Depending on the above append a certain number of zeros to the front:

if($digitCount == 2)
"00" . "23"

3) Put that into a for each loop.

foreach($arr as $value)
{
if(strlen(trim($value)) == 2)
"00" . "23";
}

Or even better use a case statement inside the for each.

Hope that helps,

D

Jerry Stuckle wrote:
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


One thing to think about. "0121" as an integer is equivalent to 81.
Numbers with leading zeros are octal.

Aug 22 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: david | last post by:
Hi, I have an application as follows: MySQL database Back-Eend linked to MS Access Front-End and ASP Web Application. I require users to enter Serial Numbers such as: 0105123567 (10...
5
by: samik_tanik | last post by:
I need to export a datagrid to Excel. I could did this. But, also need to keep the leading zeros in the data. How can I acheive this? Any help would be appreciated. -- Thanking you in...
1
by: mmmgood1 | last post by:
Help, I'm linking an excel spreadsheet in access and I have datafields with leading zeros (01021). When the file is linked in access, I get a #num in the field with the leading zeros. The zeros...
6
by: Clint Stowers | last post by:
Using A2k Exporting a query to a CSV file. The problem is any text fields (i.e. 000345) lose any leading zeros. Exporting to an excel file this problem does not exist. Tried to create a...
6
by: Rich Raffenetti | last post by:
How can one format an integer into a hex string with leading zeros? Suppose an integer is 512 which in Hex is 200. I wish to print the 4-byte integer as 0200 or even 0x0200. The HEX function...
5
by: GarryJones | last post by:
I have code numbers in 2 fields from a table which correspond to month and date. (Month, Code number) Field name = ml_mna 1 2 3 etc up to 12 (Data is entered without a leading zero)
98
by: Tak | last post by:
Some days ago, I written a mini program like this: #include <stdio.h> int main() { char c; int n; scanf("%d",&n); c = getchar();
6
by: JimmyKoolPantz | last post by:
Task: Customer wants a script of the data that was processed in a "CSV" file. Problem: Zip-Code leading zeros are dropped Basically we have a client that has requested a custom script for...
0
by: Monty | last post by:
Hi All, I am having a problem with leading zeros being stripped from fields in a CSV file when I bring them in using Jet/OleDB. In VB.Net/VS 2008, I am accessing a CSV file like so: sSQL =...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.