PHP First Program
In this page:
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
<p>Before the tag: plain HTML</p>
<?php
echo "Inside the tag: PHP executes this.";
?>
<p>After the tag: plain HTML again</p>
Login to try C/C++/Java/PHP code in the editor
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
echo "Hello", " ", "World!";
?>
Login to try C/C++/Java/PHP code in the editor
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
$name = "Alice";
echo 'Single quotes: $name stays literal';
echo "\n";
echo "Double quotes: $name is substituted\n";
?>
Login to try C/C++/Java/PHP code in the editor
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
echo 4 + 6;
?>
Login to try C/C++/Java/PHP code in the editor
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
// Missing semicolon below would trigger: parse error, unexpected token
echo "Script ran successfully.";
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: