Tuesday 7 October 2014

Formatting a number with leading zeros in PHP



I want have a variable which contains the value 1234567.

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

<?php

$num = 1234567;
echo sprintf('%08d', $num);
echo "Using str_pad".str_pad($num, 8, '0', STR_PAD_LEFT);


//To clip the first 8 digits
$p = substr(sprintf('%08d', $num),0,8);
echo "<br/>".$p;


//To clip the last 8 digits
$p = substr(sprintf('%08d', $num),-8,8);
echo "<br/>".$p;

?>

0 comments:

Post a Comment