How can I add space before numbers in php, to get output like this:
9
10
100
i m using str_pad($k,3,'',STR_PAD_LEFT) but blank space is not working
and i don't want leading zero but i want blank spaces
How can I add space before numbers in php, to get output like this:
9
10
100
i m using str_pad($k,3,'',STR_PAD_LEFT) but blank space is not working
and i don't want leading zero but i want blank spaces
You may be looking for str_pad()
.
foreach (array(1,2,3,100,1000) as $number)
echo str_pad($number, 10, " ", STR_PAD_LEFT);
However, if you want to output this in HTML, the multiple spaces will be converted to one. In that case, use
as the third parameter.
Also, if you use a font like Times or Arial, this will never produce perfectly exact results, because characters differ in width. For perfect results, you need to use a Monospace font like Courier
.
Anyway, check @Mark Baker's answer first. Right aligning the data using CSS's text-align: right
is the best solution in most cases.
When printing the numbers:
printf("%5d\n", $number);
Replace the 5
with how many spaces width minimum you want.
If you're displaying the result in a web browser, then you should be aware that browsers have this nasty little tendency to convert multiple white spaces to a single space. To check if your code is working, use the browser's "view source" option and count the spaces in the actual source rather than the rendered display.
Then look at alternatives such as
or right-aligning your values using css