add $x spaces to $phrase

rgb192
rgb192 used Ask the Experts™
on
for example
$x=3
$phrase='Hi how are you'


$phrase='Hi how are you   '
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Use str_pad http://www.php.net/str_pad

$phrase = "How are you" . str_pad(" ",3);
$phrase = strpad($phrase, 3);

or

$phrase = strpad($phrase, 3, " ");
 

Author

Commented:
that code only adds one space
Sorry...

 $phrase = str_pad($phrase, 3);

or

$phrase =  str_pad($phrase, 3, " ");
 

Author

Commented:
$phrase = str_pad($phrase, 3, " ");
$phrase = "How are you" . str_pad(" ",3);


only add one space




$phrase = str_pad($phrase, 3);
does nothing

Author

Commented:
$phrase = str_pad($phrase, 3);



does nothing
Avinash ZalaWeb Expert

Commented:
Use below.
echo 'hi how are u'.str_repeat(' ',3);
hope this helps.
Sorry, I don't know what's wrong with that str_pad function..

As Addy as told, you can use str_repeat() (NOTE THE DOT BEFORE EQUAL SIGN)


$phrase .= str_repeat(" ", 3);

Commented:
$phrase = str_pad($phrase, strlen($phrase)+$x, " ");

str_pad will pad the input string with the pad_string until the result is n characters long.
 
The second parameter is the desired length of the resulting padded string.
The original code I posted should work with one small change - the initial string should be "" rather than " "


$phrase = "How are you" . str_pad("",3);

str_pad appends 3 characters to the initial string. The deafult padding character is a space so since the OP wants a space he does not need to specify it.

Try "How are you" . str_pad("",3) . "|";

and you will notice it produces How are you   | and there are three spaces in there. However when you display it in HTML the browser **IGNORES** the extra spaces and displays only ONE of them. Try this code and you will see the difference

<?php

    echo "hello" . str_pad("", 3) . "|";
    echo "<pre>hello" . str_pad("", 3) . "|</pre>";


Author

Commented:
thanks

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial