How to Echo Tab in PHP

Olorunfemi Akinlua Feb 02, 2024
How to Echo Tab in PHP

Within our PHP application, we might use a lot of echo statements. With it comes different complications, and one of those complications is escape sequences, such as newlines, backspace, and tab.

In PHP, the tab character is a tricky one. This article will show you how to echo the tab character within your PHP code.

Echo Tab in PHP

First, to execute the tab character in PHP, you need the escape character and the letter t, \t. Though strings can be in single quotes and double quotes, the escape sequence for the tab character will not work with string literals that are in single quotes and will echo the characters.

Let’s see it in action.

<?php

echo "\tNext time of Super Story\n";
echo "The New Encounter\n";

?>

The output of the code snippet:

	Next time of Super Story
The New Encounter

Because we made use of the escape sequence within a double-quoted string literal, it worked. The code snippet also has an escape sequence for newline, \n.

Now, let’s try with single quotes.

<?php

echo "\tNext time of Super Story\n";
echo "The New Encounter\n";
echo '\tNext time of Super Story';

?>

The output of the code snippet:

	Next time of Super Story
The New Encounter
\tNext time of Super Story

You will notice that the escape sequence is printed with the contents of the string itself, which is due to the way PHP parses characters in single and double-string literals.

Olorunfemi Akinlua avatar Olorunfemi Akinlua avatar

Olorunfemi is a lover of technology and computers. In addition, I write technology and coding content for developers and hobbyists. When not working, I learn to design, among other things.

LinkedIn

Related Article - PHP Echo