php language basics
PHP Tags And Script Structure
PHP files can contain PHP code, ordinary text, or a mixture of both. The opening tag tells the PHP engine when it should start interpreting code.
<?php
echo "PHP is running\n";
// Prints:
// PHP is running
For a file that contains only PHP, leave out the closing ?> tag. This avoids accidentally sending trailing whitespace to the output, which matters when a web application needs to send headers later.
Statements End With Semicolons
Most PHP instructions end with a semicolon:
<?php
echo "first\n";
echo "second\n";
// Prints:
// first
// second
If a semicolon is missing, PHP reports a parse error. Read the reported line, then inspect the previous line too: the parser often notices the mistake when it reaches the next instruction.
Mixing HTML And PHP
PHP began as a way to add dynamic parts to HTML pages, and you will still see templates that move between HTML and PHP.
<?php
$pageTitle = 'Products';
?>
<h1><?= $pageTitle ?></h1>
<?= ... ?> is the short echo tag. It prints the value inside it. In a real template, escape untrusted values before placing them into HTML. Output escaping is covered properly in the web and security tracks.
Use full <?php tags for PHP code. Avoid the old short opening form <?, because it is less portable and can be confused with other formats.
Practice
Add A Template Heading
Create a PHP template that assigns $pageTitle = 'Orders', then prints the title inside an <h1> element using the short echo tag.
Show solution
<?php
$pageTitle = 'Orders';
?>
<h1><?= $pageTitle ?></h1>
The assignment runs as PHP. The HTML remains ordinary template text, and the short echo tag prints the title.
Fix A Missing Semicolon
<?php
echo "first\n"
echo "second\n";
Run the corrected file and confirm that it prints two lines.
Show solution
<?php
echo "first\n";
echo "second\n";
// Prints:
// first
// second
The first echo statement needed a semicolon before the second statement begins.
Remove An Unnecessary Closing Tag
<?php
echo "ready\n";
?>
Explain why the closing tag is normally omitted.
Show solution
<?php
echo "ready\n";
// Prints:
// ready
Leaving out the closing tag avoids accidental trailing output in a pure-PHP file.