Lesson 3 — Fundamentals

PHP Syntax Basics

PHP scripts are built from statements, tags, and comments, following rules that will feel familiar if you've seen C-style languages before.

Tags, Statements, and Comments

Every statement ends in a semicolon. Comments are ignored by the interpreter and come in single-line and multi-line forms, just like many other C-family languages.

PHP — Basic syntax
<?php
// This is a single-line comment
/* This is a
   multi-line comment */

$name = "Amahle";
echo "Hello, " . $name . "!";
?>

Variable Naming

Every PHP variable starts with a dollar sign, followed by a name that must start with a letter or underscore. PHP variables are case-sensitive, so $name and $Name are two different variables.

Common Mistakes

  • Forgetting the dollar sign before a variable name — PHP requires it every time a variable is referenced.
  • Mismatching case in a variable name, accidentally creating a second, unrelated variable.
  • Leaving the closing ?> tag at the very end of a pure-PHP file, which can sometimes cause unwanted whitespace output (best practice is to omit it in files with no trailing HTML).
  • Forgetting the concatenation operator (.) when joining a string and a variable together.

Professional Tip

In a file containing only PHP code (no trailing HTML), it's considered best practice to omit the closing ?> tag entirely. This avoids accidental extra whitespace or newlines being sent as output after the tag.

Your Turn

Write a short script that declares three variables (name, age, city) and echoes a sentence combining all three using the concatenation operator.

Mini Quiz

What symbol must precede every PHP variable name?