anuradha
anuradha

Reputation: 89

Add space before a numbers in PHP

How can I add space before numbers in PHP, to get output like the following?

   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 zeros, but I want blank spaces.

Upvotes: 1

Views: 7453

Answers (5)

Christian
Christian

Reputation: 1

This is what you are looking for:

str_replace(" "," ",str_pad($number, 5,'   ', STR_PAD_LEFT));

grml, look into my comment. I don't know why here the nbsp :) is gone

Upvotes: 0

Mark Baker
Mark Baker

Reputation: 212412

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.

Upvotes: 5

Sandeep Kumar M
Sandeep Kumar M

Reputation: 3851

Use the function str_pad for this purpose.

Upvotes: 0

Pekka
Pekka

Reputation: 449475

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.

Upvotes: 6

Delan Azabani
Delan Azabani

Reputation: 81384

When printing the numbers:

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

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

Upvotes: 1

Related Questions