tags:

views:

360

answers:

5

I want have a variable which contains the value 1234567.

I want it to contain exactly 8 digits i.e. 01234567.

Is there a PHP function for that?

+4  A: 

sprintf is what you need.

RC
+4  A: 

Given that the value is in $value:

  • To echo it:

    printf("%08d", $value);

  • To get it:

    $formatted_value = sprintf("%08d", $value);

That should do the trick

Kaze no Koe
+13  A: 
sprintf('%08d', 1234567);

Alternatively you can also use str_pad:

str_pad($value, 8, '0', STR_PAD_LEFT);
reko_t
+4  A: 

Simple answer

$p = 1234567;
$p = sprintf("%08d",$p);

I'm not sure how to interpret the comment saying "It will never be more than 8 digits" and if it's referring to the input or the output. If it refers to the output you would have to have an additional substr() call to clip the string.

To clip the first 8 digits

$p = substr(sprintf('%08d', $p),0,8);

To clip the last 8 digits

$p = substr(sprintf('%08d', $p),-8,8);
Peter Lindqvist
+2  A: 

Though I'm not really sure what you want to do you are probably looking for sprintf.

This would be:

<?php
    $value = sprintf( '%08d', 1234567 );
?>
Huppie