php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #33374 strval does not let me convert numbers to 'zero filled' strings
Submitted: 2005-06-17 02:26 UTC Modified: 2005-10-10 07:53 UTC
From: tiago dot freire at gmail dot com Assigned:
Status: Closed Package: Feature/Change Request
PHP Version: 5.0.4 OS: GNU/Linux
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: tiago dot freire at gmail dot com
New email:
PHP Version: OS:

 

 [2005-06-17 02:26 UTC] tiago dot freire at gmail dot com
Description:
------------
Suppose I want to build a string with fixed length (for whatever reason) by appending a number to a string.

//I want strings like 'foo0001','foo0002','foo0010' etc
for ($i=1;$i<1000;$i++)
{
    $string = 'foo'.$i;
}
strval could be useful IF it accepted a second (int) parameter to tell it: 
    "This number will have <int parameter> characters in string form,fill it to the left with zeroes"

With this behaviour,this would work:
for ($i=1;$i<1000;$i++)
{
    $string = 'foo'.strval($i,4);//This would give me '0001'
}
What about floats? Another parameter.

Explained by example:
for ($i=1;$i<1000;$i++)
{
    $string = 'foo'.strval($i,4,3);//This would give me '0001.000'
}

For completeness:
$number = 123456789;
$string = 'bignumber: '.strval($number,5);
Will result in the string 'bignumber123456789', since I asked for less characters than the number has.


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2005-06-17 09:25 UTC] nickj-phpbugs at nickj dot org
Please see str_pad, as this already does what you're looking for: http://php.net/str-pad

Example code:

for ($i=1;$i<=101;$i++) {
   // This gives 'foo0001'
   print "foo" . str_pad($i, 4, "0", STR_PAD_LEFT) . "\n";
}
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Tue Aug 05 17:00:03 2025 UTC