View Full Version : Str_pad only working when padding is not a space

07-23-2007, 01:13 AM

I'm padding out entries in an array to the length of the last entry (which will always be the longest).

I want the padding to be a space as it should be by default. The padding is only working if the character isn't a space.

How can I fix this?

$packets = (count($sizes))-1; // Count the number of different packet sizes
$slength = strlen($sizes[$packets]); // Works out the length of the last entry in sizes
$plength = strlen($prices[$packets]); // Works out the length of the last entry in prices
$pad = '_';
while ($i <= $packets){
$output3[] = '<b>'.str_pad($sizes[$i], $slength, $pad , STR_PAD_LEFT); // Pads all packet sizes to the length of the longest one
$output3[] = ''.str_pad($prices[$i], $plength, $pad , STR_PAD_LEFT); // Pads all packet prices to the length of the longest one

If I put a space into the string that is to be used to pad out the entries nothing happens, no padding whatsover.

Any help would be appreciated!

07-23-2007, 02:11 AM

07-23-2007, 02:14 AM
Edit: too slow again, basically says the same as above ^^

If you are outputting this to a browser, spaces mean nothing as far as formatting and alignment goes (unless you are using something like the <pre></pre> tags). Groups of spaces are condensed to a single space. To do what you want, you need to use a non-breaking-space '&nbsp;' (use all the characters between the single-quotes.)

07-23-2007, 02:38 AM
I'd already tried &nbsp; without the quotes which had caused an error (forgot to mention that).

Doing it with quotes literally adds that as the padding rather than the space.

Hm, ok I've just outputted the length of the one that should have been padded, and you are right, it has been padded with the space and the browser just isn't showing it.

Thats kind of annoying :-(

I think I may have a way to get around it though...

07-23-2007, 03:52 AM
Instead of using lengths of strings to align columns of values, use some text alignment properties - http://w3schools.com/css/tryit.asp?filename=trycss_text-align

07-23-2007, 04:09 AM
I did try doing that yesterday but in this instance it wasn't suitable.

Anyway I got it to work with a bit of clever thinking :D

The string is padded out and then the padded character is replaced with two empty spaces.

It works perfectly!