echo and Embedding PHP in HTML
Your first PHP statement, living happily inside a web page
Time to write some actual PHP. The very first thing every PHP programmer learns is echo, which simply means: send this text to the page.
The opening and closing tags
PHP code must live between <?php and ?>. Think of these tags as a door: when the server reaches <?php, it steps into PHP mode and starts running code. When it reaches ?>, it steps back out and treats everything as plain HTML again.
<?php
echo "Hello, world!";
?>This tiny program outputs the text Hello, world!. Two details deserve your attention:
- The text sits inside double quotes. Quoted text is called a string, and you will meet strings properly in the next lesson.
- The line ends with a semicolon. In PHP, every statement ends with
;the way an English sentence ends with a period. Forgetting the semicolon is the most common beginner error in PHP, so when something breaks, check your semicolons first.
PHP and HTML in the same file
Here is where PHP starts to feel made for the web. You can drop in and out of PHP anywhere in an HTML file:
<h1>My First Dynamic Page</h1>
<p>Today's lucky number is <?php echo 7; ?>.</p>
<p>This paragraph is plain HTML again.</p>When the server runs this file, the visitor receives:
<h1>My First Dynamic Page</h1>
<p>Today's lucky number is 7.</p>
<p>This paragraph is plain HTML again.</p>The PHP vanished and left its output behind. That swap, code in, HTML out, is the heartbeat of every PHP site.
echo can output HTML too
The text you echo does not have to be plain words. It can contain HTML tags, and the browser will treat them like any other markup:
<?php
echo "<h2>Fresh from the server</h2>";
echo "<p>This heading and paragraph were both printed by PHP.</p>";
?>Style tip: real projects usually keep most of the page as HTML and use small pieces of PHP only where something needs to change. A file that is one giant echo is much harder to read than HTML with a few PHP islands in it.
You now know how to make PHP say things. Next up: teaching it to remember things.
Quick check
Q1 What does the echo statement do?
Q2 How does almost every PHP statement end?
Want to save your progress? It's free.
Create a free account