php echo is one of the most used constructs in php. The echo is not a function, but a language construct and allows us as php programmers to output one or more strings.
echo "Hello World!"; // Output: Hello World!
The php echo statement is one of the most used and most useful statements in the php programming language.
With echo, in php, you can pass one string or multiple strings separated by commas.
echo "Hello World!"; // Output: Hello World! echo "Hello"," World!"; // Output: Hello World!
You can also pass other types of data to echo, and php will attempt to coerce these data types into a string. For integers, this works, but for arrays, a warning will be thrown.
echo 1; // Output: 1 echo [0,1]; // Output: Warning: Array to string conversion on line 2 Array
If we want to output an array, we should use the json_encode function first, and then pass it to echo.
echo json_encode([0,1]); // [0,1]
Using echo to Output A String in php
Outputting a string using echo is very easy. All we need to do is pass a string to the php echo statement.
echo "This is a string we are outputting with echo!"; // Output: This is a string we are outputting with echo!
How to Use echo in php to Output Multiple Strings
Outputting multiple strings using echo is very easy. All we need to do is pass the strings to the php echo statement separated by commas.
echo "This is a string.", " This is a second string."; // Output: This is a string. This is a second string.
One thing to note here is that the strings are all printed on the same line. To output multiple strings to multiple lines, you should use \r\n.
echo "This is a string.", "\r\nThis is a second string."; // Output: This is a string. This is a second string.
Using echo to Output HTML in php
One of the most useful ways to use the php echo is when outputting HTML to a web page. Many times, as web developers, we want to design pages which are dynamic and with echo, we can accomplish this.
To output HTML using echo and php, we just need to build a string which contains our HTML.
Let’s say I want to use php to create a web page. In this web page, I want to echo the title and a summary paragraph to the browser.
We can do this easily with the following php code:
echo "<h2>Page Title</h2><p>Page Summary</p>";
This will output the following HTML:
How to Output a Variable Using echo in php
We can also use echo to output php variables. To do this, we just need to pass the variable to echo:
$var1 = "A string to output with echo"; echo $var1; // Output: A string to output with echo
If we have multiple variables we want to output, we can concatenate them or pass them separated by commas.
$var1 = "String 1"; $var2 = "String 2"; echo $var1 . ' ' . $var2; // Output: String 1 String 2 echo $var1, ' ', $var2; // Output: String 1 String 2
Hopefully this article has been helpful for you to understand all the ways you can use echo in php to output strings.