Lesson 2 of 12

PHP Syntax and Variables

Every language has grammar rules, and PHP is no different. Once you know a handful of them – where statements end, how to write comments and how to name variables – you can read almost any beginner PHP script. This lesson builds on the PHP introduction and covers the PHP syntax you will use in every lesson that follows.

Basic PHP syntax rules

  • PHP code sits between <?php and ?>. In files that contain only PHP, leave out the closing tag.
  • Each statement ends with a semicolon ;. Forgetting it is the most common beginner error.
  • Whitespace and line breaks are ignored, so you can indent code to make it readable.
  • Keywords such as echo, if and function are not case-sensitive, but variable names are. $city and $City are two different variables.

Write keywords in lowercase anyway. It is the convention in the PHP community and in the PSR-12 coding style that most projects follow.

Comments

Comments are notes for humans. PHP skips them completely. Use them to explain why a piece of code exists, not to repeat what it obviously does.

StyleUse
// textSingle-line comment, the most common kind.
# textAlso single-line; less common in modern code.
/* text */Multi-line comment, or to switch off a block of code while testing.
/** text */A DocBlock, used to document functions and classes for editors and tools.

Printing output: echo and print

echo sends text to the output. It can take several values separated by commas. print does almost the same job but takes only one value. In practice most developers use echo. There is also a short form, <?= $value ?>, which is the same as <?php echo $value; ?> and is popular inside HTML templates.

Variables

A variable is a named box that holds a value so you can use it later. In PHP every variable name starts with a dollar sign $. You create a variable simply by assigning a value to it with =; there is no separate declaration keyword like let in JavaScript.

<?php
$studentName = "Arjun";
$city = "Madurai";
$age = 21;

echo "Name: ", $studentName, "\n";
echo "City: $city\n";
echo "Next year $studentName will be ", $age + 1, ".\n";

$city = "Coimbatore"; // a variable can be given a new value
echo "Moved to $city";
Output
Name: Arjun
City: Madurai
Next year Arjun will be 22.
Moved to Coimbatore

Inside double quotes, PHP replaces variable names with their values. This is called interpolation. The \n is a new-line character; in a browser you would use an HTML tag such as <br> or a new paragraph instead. You will learn more about quotes in PHP Strings.

Naming rules

  • A name starts with $, followed by a letter or underscore.
  • After that you can use letters, numbers and underscores: $total2 is fine, $2total is not.
  • No spaces or hyphens. $first-name is read as $first minus name.
  • Choose clear names. $orderTotal tells the reader far more than $x. Most PHP projects use camelCase for variables.

PHP is dynamically typed

You never state the type of a variable. PHP works it out from the value, and the same variable can later hold a value of another type. That is flexible, but it can also hide mistakes. The next lesson, PHP Data Types, shows how to inspect types and how declare(strict_types=1); makes PHP stricter.

Watch out: Using a variable that has never been assigned gives the warning Undefined variable and the value null. Always give a variable a value before you read it. The null coalescing operator ??, covered in PHP Operators, is a clean way to supply a default.

Constants

Some values should never change while the script runs, such as a tax rate or a site name. Store those in a constant. Constants have no $ sign and are written in UPPER_CASE by convention. You can create them with the const keyword or with the define() function.

<?php
const SITE_NAME = "Chennai Spice Kitchen";
define('GST_RATE', 0.05);

$price = 400;
$tax = $price * GST_RATE;

echo SITE_NAME . "\n";
echo "Price: $price, GST: $tax\n";
echo "Total: " . ($price + $tax);
Output
Chennai Spice Kitchen
Price: 400, GST: 20
Total: 420

The dot . joins strings together. Constants are not interpolated inside double quotes, which is why the example joins SITE_NAME with a dot. A constant cannot be given a new value: writing SITE_NAME = "x"; is a syntax error, and defining the same name twice produces a warning while the original value stays. That is exactly the protection you want.

Tip: Prefer const for simple values defined at the top of a file. define() is useful when the name or value is only known while the script runs, for example inside an if block.

Putting it together

Most real scripts follow the same pattern: set up some constants, store input or data in variables, work with them, then print the result. In the following lessons you will build on this PHP syntax with data types, strings, operators and conditions.

Further reading

Key takeaways

  • Every PHP statement ends with a semicolon; whitespace is ignored.
  • Comments use //, # or /* ... */ and are skipped by PHP.
  • Variables start with $, are created by assignment and their names are case-sensitive.
  • Double-quoted strings replace variable names with their values.
  • Constants (const or define()) hold values that must not change and have no $.

Quick quiz

Check what you learned – pick an answer.

1. Which of these is a valid PHP variable name?

2. What does echo "City: $city"; print if $city is "Salem"?

3. How do you read a constant named MAX_SEATS?

Practice exercise

Create a constant SHOP with the value "Mysore Silks", and variables for a product name ("Silk saree") and a quantity (3). Print the line: Mysore Silks: 3 x Silk saree.

Show a hint

Join the constant to a double-quoted string with the dot operator.

Show the solution
<?php
const SHOP = "Mysore Silks";
$product = "Silk saree";
$quantity = 3;

echo SHOP . ": $quantity x $product";

Progress is saved in this browser only.