← Back to PHP Course | Chapter 1: Introduction & Basics | Lesson 4 of 13

PHP First Program

Opening and Closing Tags

Every block of PHP code starts with <?php and ends with ?>. The web server treats anything between those tags as PHP to execute, and anything outside them — including surrounding HTML — as plain text to pass through untouched, which is what lets a single file mix markup and logic.

Example: Opening and Closing Tags

php
<p>Before the tag: plain HTML</p>
<?php
echo "Inside the tag: PHP executes this.";
?>
<p>After the tag: plain HTML again</p>

The echo Statement

echo sends text (or the result of an expression) straight into the page's output. It's technically a language construct rather than a function, so you can call it without parentheses, and you can pass it several comma-separated values in one call.

Example: The echo Statement

php
<?php
echo "Hello", " ", "World!";
?>

Handling Simple Strings

Text in PHP goes inside single or double quotes, but they behave differently: single quotes print almost everything literally (including a $variable reference as plain text), while double quotes actively evaluate variables and interpret escape sequences like \n for a newline.

Example: Handling Simple Strings

php
<?php
$name = "Alice";
echo 'Single quotes: $name stays literal';
echo "\n";
echo "Double quotes: $name is substituted\n";
?>

Simple Math Output

PHP evaluates arithmetic expressions the moment it reaches them, so echo 4 + 6; doesn't print the text '4 + 6' — it computes the sum first and outputs 10. This is the basis for anything more complex you'll do with numbers later, like calculating totals or formatting prices.

Example: Simple Math Output

php
<?php
echo 4 + 6;
?>

Running Your First Script

Once you write and run a script, check the output carefully against what you expected — a missing semicolon or an unclosed quote is the most common first-script error, and PHP's error message will usually point you to the exact line where it got confused.

Example: Running Your First Script

php
<?php
// Missing semicolon below would trigger: parse error, unexpected token
echo "Script ran successfully.";
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.