views:

60

answers:

4

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

A: 

Use str_pad

http://php.net/manual/en/function.str-pad.php

Sandy
+5  A: 

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.

Pekka
+1 for browser space reduction
Mark Baker
meh. @Mark Baker gave the right answer: do it in CSS. At least you didn't advise the use of `printf` and family though.
aaronasterling
anuradha
@anu I'm sorry, `str_pad` doesn't work that way. Use normal spaces, and replace them afterwards: `$string = str_replace(" ", " ", $string`;
Pekka
A: 

When printing the numbers:

printf("%5d\n", $number);

Replace the 5 with how many spaces width minimum you want.

Delan Azabani
+3  A: 

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

Mark Baker
+1 for css mention. This is a presentational issue, not a PHP issue. CSS is the correct and __easy__ way to handle this.
aaronasterling