adding zeroes in front

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
byenary
Forum Newbie
Posts: 10
Joined: Mon Apr 03, 2006 6:15 am

adding zeroes in front

Post by byenary »

Hello,

Ive created an array form a query which contains numbers like 5 , 45, 2, 846
But i should have it as 00005 , 00045 , 00002, 00846
What kind of instrucitions whould do this in a nice way...?

THx
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post by Benjamin »

From the manual.. http://www.php.net/str_pad

Code: Select all

<?php
$input = "Alien";
echo str_pad($input, 10);                      // produces "Alien     "
echo str_pad($input, 10, "-=", STR_PAD_LEFT);  // produces "-=-=-Alien"
echo str_pad($input, 10, "_", STR_PAD_BOTH);   // produces "__Alien___"
echo str_pad($input, 6 , "___");               // produces "Alien_"
?>
So...

Code: Select all

echo str_pad($input, 5, "0", STR_PAD_LEFT);
May be close to what your looking for

But even after you pad it, you will need to ensure that it's treated as a string..

Code: Select all

$input = (string) $input;
Otherwise the 0's may be removed..
Post Reply