How to Create a Space in PHP Code

By Sean Mann

Adding multiple white spaces and line breaks in PHP code is important for formatting and displaying text properly on a web page. Strings from other software may be using different spacing characters and need to be converted to HTML tags. Unfortunately, some computer architectures use different spacing characters than others. Creating spaces in PHP is done mainly through the "echo" function.

Step 1

Open the PHP file in a text editor, such as Windows Notepad.

Step 2

Add a single space between PHP variables by adding the code "echo $variable1 ." ". $variable2;."

Step 3

Add multiple spaces by adding the code "echo $variable1 ."  ". $variable2;." The " " entity represents a non-breaking space. Using " " frequently doesn't work because web browsers collapse multiple spaces into one.

Step 4

Add a space as a line break with the code "echo "\r\n"", "echo """ or "echo "\n"." The "\n" character represents a new line and the "\r" character represents a carriage return.

Step 5

Call the PHP "nl2br" function to replace every "\r", "\n", "\n\r" and "\r\n" entity in a string with an HTML line break, "
" or "", by adding the code "echo nl2br("line1\nline2");." This will output "line1
" and then "" on the next line.

Step 6

Save the PHP file, close it and then load it on your server.

Tips & Warnings

  • PHP code must be contained inside "" tags.