PHP · Beginner
PHP Syntax and Your First Program
In short: A PHP script starts with the <?php tag; everything after it is code until the file ends. Each statement ends with a semicolon, echo writes text to standard output, and fgets(STDIN) reads one line of input. The closing ?> tag is optional and best left out of files that contain only PHP.
What a PHP file looks like
PHP was designed to be dropped into HTML pages, so the interpreter treats a file as plain text to be printed until it meets the <?php tag. From that tag onwards it reads code. A command-line script therefore begins with <?php on the very first line, with nothing in front of it: even a blank line or a space before the tag is text, and text is printed. The closing ?> tag switches back to text mode. In a file that contains only PHP you leave it out, because anything after it, including an invisible trailing newline, would be printed too.
Code is a sequence of statements, and every statement ends with a semicolon. Line breaks and indentation are for people, not for the interpreter: one statement may span several lines, and two statements may share one line. The semicolon is what separates them. Forgetting one is the most common first error, and PHP reports it as a parse error naming the line after the missing semicolon, because that is where it noticed something was wrong.
echo writes to standard output. It is a language construct rather than a function, which is why it needs no parentheses and accepts several values separated by commas: echo "Total: ", 12, "\n"; prints all three in order. The dot operator . joins strings into one value first, so echo "a" . "b"; prints the same as echo "a", "b";. Nothing adds a line break for you; write "\n" where you want one.
Input on the command line arrives through the STDIN stream. fgets(STDIN) reads one line, including its trailing newline, and returns false when there is no more input. Wrapping it in trim() removes the newline and any surrounding spaces, which is almost always what you want. Whatever you read is a string, even if it looks like a number, so (int) or (float) converts it before arithmetic.
Comments start with // or # and run to the end of the line; /* ... */ comments can span lines. Keywords such as echo and built-in function names such as strlen are case-insensitive, but variable names are case-sensitive: $name and $Name are two different variables. Write everything in lowercase and the question never comes up. A script is run with php main.php; the site runs your program exactly that way and shows what it printed.
Syntax
<?php
// statement; statement; ...
echo "text", $variable, 42, "\n"; // several values, printed in order
echo "joined " . "with a dot" . "\n"; // one string built with .
$line = fgets(STDIN); // one line of input, newline included, or false at end
$clean = trim(fgets(STDIN)); // the same line without the newline
$number = (int) trim(fgets(STDIN)); // converted to an integer
/* a comment
over several lines */
# another single-line commentNo closing ?> tag in a pure PHP file. Every statement ends with a semicolon; a line break on its own ends nothing.
Printing several lines
A notice for a bakery counter, printed with four echo statements that mix text and numbers.
<?php
echo "Hollow Oak Bakery\n";
echo "Opening hours: 7:00 to 15:00\n";
echo "Loaves baked today: ", 48, "\n";
echo "Sourdough" . " and " . "rye" . "\n";Output
Hollow Oak Bakery Opening hours: 7:00 to 15:00 Loaves baked today: 48 Sourdough and rye
Each \n ends a line; without it the four outputs would run together on one line. The third statement passes three values to echo, and the number 48 is printed as text. The fourth builds one string with the dot operator before printing it. Both styles produce the same output; commas are slightly cheaper because no combined string is built, but readability matters more.
Reading a line of input
The program reads a customer name and a number of loaves, then prints an order summary.
<?php
$name = trim(fgets(STDIN));
$loaves = (int) trim(fgets(STDIN));
echo "Order for ", $name, "\n";
echo "Loaves: ", $loaves, "\n";
echo "Slices: ", $loaves * 12, "\n";Input given to the program: Priya ↵ 3
Output
Order for Priya Loaves: 3 Slices: 36
The first fgets returns "Priya\n"; trim strips the newline so the name prints cleanly. The second line is "3", a string, and (int) turns it into the integer 3 so that $loaves * 12 is arithmetic rather than a type error. Reading, converting and then printing is the shape of nearly every exercise on this site.
Comments, whitespace and case
Three comment styles, a statement split across lines, and keywords written in unusual case to show what PHP ignores.
<?php
// A single-line comment: ignored by PHP.
# Another single-line comment.
/* A block comment
can span several lines. */
$greeting = "good morning";
echo strtoupper(
$greeting
), "\n"; // one statement over three lines
ECHO STRLEN($greeting), "\n"; // keywords and function names are case-insensitive
echo $greeting, "\n";Output
GOOD MORNING 12 good morning
The comments produce nothing. The strtoupper call is split over three lines and still counts as one statement because the semicolon comes at the end. ECHO and STRLEN work exactly like echo and strlen, but $Greeting would not work in place of $greeting: variables are case-sensitive. Use lowercase for keywords and functions; the uppercase form is shown here only to make the rule visible.
Common mistakes
Something before the opening tag
Why it goes wrong: A blank line, a space or a stray character before
<?phpis outside PHP mode, so it is printed as output. The program then fails a test because its output starts with an unexpected empty line.Fix: Make
<?phpthe first characters of the file, and do not add a closing?>tag at the end.PHP · fix<?php echo "first line of output\n";Missing semicolon
Why it goes wrong:
echo "a"followed byecho "b";on the next line is a parse error reported on the second line, because PHP only discovers the problem when it reads the next keyword.Fix: End every statement with
;. When the reported line looks fine, check the line above it.Joining strings with +
Why it goes wrong:
+is arithmetic."Total: " + 5throws aTypeErrorin PHP 8 because"Total: "is not a number.Fix: Use the dot operator to join strings, or pass separate values to echo.
PHP · fix<?php echo "Total: " . 5, "\n"; echo "Total: ", 5, "\n";Forgetting the dollar sign
Why it goes wrong:
name = "Ada";is a parse error, andecho name;is treated as a constant calledname, which throws anErrorbecause it is undefined.Fix: Every variable, when written and when read, starts with
$.
Ways to write output
| Statement | What it prints | Notes |
|---|---|---|
| echo "a", 1, "\n"; | a1 and a newline | several values, no string built |
| echo "a" . 1 . "\n"; | a1 and a newline | one joined string |
| print "a\n"; | a and a newline | one value only; returns 1, so it can sit inside an expression |
| printf("%s: %d\n", "a", 1); | a: 1 and a newline | formatted output, covered in the strings lesson |
Where you use this
Every exercise on this site is a small command-line program: read lines from STDIN, compute, print with echo. The same syntax runs the other way PHP is normally used, embedded in a web page, where the file is mostly HTML and PHP appears only inside tags. Understanding that text outside the tags is output explains both worlds at once: the exercise script is a file that is one big PHP block, and the web page is a file that switches into PHP only where it needs to compute something.
<ul>
<?php foreach (["rye", "spelt"] as $loaf): ?>
<li><?= $loaf ?></li>
<?php endforeach; ?>
</ul>Key points
<?phpmust be the first thing in the file; leave out the closing?>in pure PHP files.- Statements end with
;; line breaks and indentation do not matter to the interpreter. echoprints one or more comma-separated values;.joins strings.fgets(STDIN)reads one line as a string;trimremoves the newline and(int)converts.- Comments use
//,#or/* */. - Keywords and function names ignore case; variable names do not.
Try it yourself
The program greets the person whose name it reads. Add a second line that prints how many letters the name has, in the form Your name has 7 letters., using strlen.
<?php
$name = trim(fgets(STDIN));
echo "Hello, ", $name, "\n";
MarisolHello, Marisol
Your name has 7 letters.<?php
$name = trim(fgets(STDIN));
echo "Hello, ", $name, "\n";
echo "Your name has ", strlen($name), " letters.\n";
Practise this
Related lessons
- Variables and Types in PHPHow PHP variables are named and assigned, the scalar types int, float, string, bool and null, how input text becomes numbers, and where type juggling bites.8 min
- Conditions and Loops in PHPBranch with if, elseif, else and match, repeat with while, for and foreach, and control loops with break and continue, with PHP 8 examples that read input.9 min
Frequently asked questions
Do I need the closing ?> tag at the end of a PHP file?
No. In a file that contains only PHP code the closing tag is optional, and leaving it out is the safer choice: any newline or space after ?> is printed as output, which corrupts the result of a script and, on the web, can break HTTP headers. Use ?> only when you switch back to HTML in the same file.
Is PHP case-sensitive?
Partly. Variable names are case-sensitive, so $total and $Total are different variables. Keywords such as echo, if and function, and the names of functions and classes, are case-insensitive. The convention is lowercase for keywords and functions, and camelCase or snake_case for variables.
What is the difference between echo and print in PHP?
Both write to standard output. echo accepts several comma-separated values and returns nothing; print accepts exactly one value and returns the integer 1, so it can be used inside an expression. In practice echo is used almost everywhere.
How this page was checked. Every program on it was run with PHP 8.4 at build time by the publishing checks, and the output shown is what it printed. Running PHP inside the browser is not available yet, so the Run button is absent rather than pretending; copy the code and run it with PHP 8.4 locally.