PHP becomes useful when a script can make decisions, repeat work, calculate values, and generate output dynamically. A static page always sends the same content to the browser. A PHP file can calculate a total, test a value, choose a message, scan a list, or include a reusable file while the request is being processed on the server.
This tutorial focuses on the PHP statements that make that possible. The examples use plain text output, so the behavior is easy to see. In a real web page, the text produced by print is sent to the browser, and the browser treats it as page content.
Context and Scope
A PHP script is a sequence of statements placed inside a PHP scripting block. A statement usually ends with a semicolon. PHP keywords such as print, if, else, switch, for, and while are not case-sensitive, but writing them in lowercase keeps code easier to read.
The statement types covered here are:
- Assignment statements, used to give values to variables.
- Print statements, used to send output to the browser.
- If statements, used to run code only when a condition is true.
- Switch statements, used when the same value is compared with several alternatives.
- For loops, used when repetition follows a clear counting pattern.
- While loops, used when repetition depends on a condition.
- Do while loops, used when the loop body must run at least once.
- Include and require statements, used to load and evaluate another PHP file.
The foreach statement is also a major PHP statement, but it is better introduced when arrays are the main topic.
A small script can use several of these statements together:
<?php
$visitorName = "Nora";
$visits = 3;
if ($visits > 1) {
print "Welcome back, " . $visitorName . "\n";
} else {
print "Welcome, " . $visitorName . "\n";
}
?>
This script assigns values, checks a condition, joins strings, and prints the result. Those ideas are the foundation of most beginner PHP programs.
Assignment Statements
An assignment statement stores the value of an expression in a variable or an array element. The equals sign does not mean mathematical equality. It means "set the variable on the left to the value on the right".
<?php
$price = 120;
$quantity = 4;
$total = $price * $quantity;
print "Total: " . $total . "\n";
?>
The variable $total receives the result of $price * $quantity. If $price or $quantity changes later, $total does not automatically change. It keeps the value assigned to it until another assignment updates it.
<?php
$count = 10;
$count = $count + 5;
print $count;
?>
The second assignment uses the existing value of $count, adds 5, and stores the new value back into $count. The output is:
15
Arithmetic Expressions
Arithmetic expressions can contain numbers, variables, array elements, function calls, parentheses, and arithmetic operators.
Common arithmetic operators are:
| Operator | Meaning |
|---|---|
+ |
Addition |
- |
Subtraction |
* |
Multiplication |
/ |
Division |
% |
Remainder after division |
The % operator is useful when you need the remainder. For example, 17 % 5 gives 2 because 17 divided by 5 leaves 2 over.
<?php
$items = 17;
$boxSize = 5;
$leftOver = $items % $boxSize;
print "Items not fitting into full boxes: " . $leftOver;
?>
PHP evaluates arithmetic expressions in a predictable order:
- Parentheses are handled from the inside out.
- Unary plus and unary minus are applied.
- Multiplication, division, and modulus are applied from left to right.
- Addition and subtraction are applied from left to right.
When the expression is not obvious, add parentheses. They make the intended calculation clear to the next developer.
<?php
$base = 18;
$bonus = 7;
$penalty = 4;
$result = (($base + $bonus) * 2 - $penalty) / 3;
print "Result: " . $result;
?>
Without the parentheses, the expression would still be valid PHP, but it would be much easier to misread.
Short Assignment Notation
PHP provides shorter notation for common updates:
| Short form | Same meaning |
|---|---|
$x++; |
$x = $x + 1; |
$x--; |
$x = $x - 1; |
$x += $y; |
$x = $x + $y; |
$x -= $y; |
$x = $x - $y; |
$x *= $y; |
$x = $x * $y; |
$x /= $y; |
$x = $x / $y; |
$x %= $y; |
$x = $x % $y; |
Use these when they improve readability. They are common in loops and counters.
<?php
$stock = 20;
$soldToday = 6;
$stock -= $soldToday;
$stock++;
print "Current stock: " . $stock;
?>
The script subtracts sold items, then adds one returned item.
String Expressions
A string expression produces text. It can be a literal string, a variable containing text, a function call returning text, or several values joined together.
PHP uses the dot operator (.) to concatenate strings.
<?php
$firstName = "Elin";
$role = "editor";
$message = "User " . $firstName . " has role " . $role;
print $message;
?>
The output is:
User Elin has role editor
PHP can also convert numbers to strings when they are part of a concatenation chain.
<?php
$product = "Notebook";
$units = 8;
$unitPrice = 25;
$line = $product . ": " . $units . " units, total " . ($units * $unitPrice);
print $line;
?>
The arithmetic expression is wrapped in parentheses so PHP calculates it before joining it to the surrounding strings.
Short String Joining Notation
The .= operator appends text to an existing string.
<?php
$summary = "Order accepted";
$summary .= ", payment pending";
$summary .= ", warehouse notified";
print $summary;
?>
This is equivalent to repeatedly writing $summary = $summary . "...";, but it is more compact.
Logical Expressions
A logical expression produces either TRUE or FALSE. Logical expressions are used heavily in conditions and loops.
A logical expression can be:
TRUEorFALSE.- A variable containing a logical value.
- A function call returning a logical value.
- A comparison such as
$age >= 18. - A combination of logical expressions using
&&,||,XOR, or!.
Common logical operators are:
| Operator | Meaning |
|---|---|
! |
Not |
&& |
True only when both sides are true |
| ` | |
XOR |
True when exactly one side is true |
<?php
$age = 21;
$hasTicket = TRUE;
$isBlocked = FALSE;
$canEnter = ($age >= 18) && $hasTicket && !$isBlocked;
if ($canEnter) {
print "Entry allowed";
} else {
print "Entry denied";
}
?>
The expression reads naturally: age must be at least 18, the person must have a ticket, and the person must not be blocked.
Truthy and Falsey Values
PHP can treat non-logical values as logical values in conditions. The following values behave as false:
- The logical value
FALSE. - The number
0. - The string
"0". - The empty string
"".
Other numbers and most non-empty strings behave as true.
<?php
$value = "0";
if ($value) {
print "Value is treated as true";
} else {
print "Value is treated as false";
}
?>
The output is:
Value is treated as false
This behavior is useful to understand, but do not overuse it. Conditions are easier to maintain when they show exactly what they are testing.
Prefer this:
<?php
$quantity = 0;
if ($quantity == 0) {
print "No items selected";
}
?>
Instead of relying on a bare variable when the intent is numeric comparison.
Checking Whether a Variable Exists
The isset function returns FALSE when a variable has not been initialized or has been assigned NULL. Otherwise, it returns TRUE.
<?php
if (!isset($couponCode)) {
print "No coupon was supplied";
}
?>
This is useful before using optional values.
Print Statements
A print statement sends characters to the browser. The expression after print can be a string, a number, a variable, a concatenated expression, or a logical expression.
<?php
$name = "Ravi";
$day = "Monday";
print "Hello " . $name . ". Today is " . $day . ".";
?>
Output:
Hello Ravi. Today is Monday.
In web programming, this output is not sent directly to a terminal. It becomes part of the response that the browser receives. That is why PHP can generate dynamic page content.
Newlines in Generated Output
The escape sequence \n inserts a newline character into the generated output. This can make the generated source easier to inspect, but it does not necessarily create a visible line break on the web page. Visual layout is controlled by the browser.
<?php
print "First generated line\n";
print "Second generated line\n";
?>
When debugging generated output, newlines can make the returned content easier to read.
Printing Logical Values
PHP prints logical values in a way that surprises many beginners:
TRUEis printed as1.FALSEis printed as an empty string.
<?php
$approved = TRUE;
$archived = FALSE;
print "approved=" . $approved . "\n";
print "archived=" . $archived . "\n";
?>
Output:
approved=1
archived=
When writing user-facing messages, do not print logical values directly. Convert them into words yourself.
<?php
$isActive = FALSE;
if ($isActive) {
print "Status: active";
} else {
print "Status: inactive";
}
?>
If Statements
An if statement runs code only when a condition is true.
<?php
$balance = 75;
$cost = 60;
if ($balance >= $cost) {
print "Purchase can continue";
}
?>
The basic form is:
if (condition) statement;
Most real scripts use a statement group, which is a set of statements wrapped in braces.
<?php
$balance = 75;
$cost = 60;
if ($balance >= $cost) {
$balance -= $cost;
print "Purchase accepted\n";
print "Remaining balance: " . $balance;
}
?>
Comparison Operators
Conditional expressions often compare two values.
| Operator | Meaning |
|---|---|
== |
Equal to |
!= |
Not equal to |
> |
Greater than |
>= |
Greater than or equal to |
< |
Less than |
<= |
Less than or equal to |
The most important beginner mistake is confusing = and ==.
<?php
$status = "ready";
if ($status == "ready") {
print "Start processing";
}
?>
Use == when comparing values. Use = only when assigning a value.
Elseif and Else
An if statement can be extended with elseif and else.
<?php
$score = 74;
if ($score >= 90) {
print "Grade: excellent";
} elseif ($score >= 70) {
print "Grade: good";
} elseif ($score >= 50) {
print "Grade: pass";
} else {
print "Grade: retry";
}
?>
PHP checks the conditions from top to bottom. Once one condition is true, its block runs, and the remaining branches are skipped. The else branch is the fallback when no previous condition is true.
Switch Statements
A switch statement is useful when the same variable is compared with several fixed values.
<?php
$deliveryDay = "Sunday";
switch ($deliveryDay) {
case "Saturday":
print "Weekend delivery slot";
break;
case "Sunday":
print "Limited delivery slot";
break;
default:
print "Standard delivery slot";
break;
}
?>
The switch checks $deliveryDay, finds the matching case, and starts executing statements from there. The break statements matter. Without break, execution continues into the next case.
A switch is often clearer than a long if, elseif, elseif, else chain when every branch is based on the same variable.
For Loops
A for loop is best when you know how the counter should start, how long it should continue, and how it should change after each pass.
<?php
for ($number = 2; $number <= 20; $number += 2) {
print $number * $number . "\n";
}
?>
This prints the squares of the first ten positive even numbers.
A for loop has three parts inside parentheses:
for (initial assignment; condition; update)
For example:
<?php
for ($i = 0; $i < 5; $i++) {
print "Counter is " . $i . "\n";
}
?>
The flow is:
- Set
$ito0. - Check whether
$i < 5. - Run the loop body if the condition is true.
- Run
$i++. - Repeat from the condition check.
For loops are often used to walk through array positions when the array uses consecutive numeric indexes.
<?php
$tasks = array("Plan", "Build", "Test", "Deploy");
for ($i = 0; $i < 4; $i++) {
print "Task " . $i . ": " . $tasks[$i] . "\n";
}
?>
Output:
Task 0: Plan
Task 1: Build
Task 2: Test
Task 3: Deploy
While Loops
A while loop repeats as long as a condition remains true. It is useful when the number of repetitions is not the main idea, or when the loop should stop because something has been found.
<?php
$names = array("Mira Lane", "Oskar Reed", "Lea Stone", "Ivan Moss");
$numbers = array(310, 455, 612, 208);
$searchName = "Lea Stone";
$found = "no";
$position = 0;
while ($position < 4 && $found == "no") {
if ($names[$position] == $searchName) {
$found = "yes";
} else {
$position++;
}
}
if ($found == "yes") {
print $searchName . " has number " . $numbers[$position];
} else {
print $searchName . " was not found";
}
?>
A while loop checks the condition before each run. If the condition is false at the beginning, the loop body never runs.
The loop body must contain a way for the condition to eventually become false. Otherwise, the loop can run forever.
<?php
$i = 1;
while ($i * $i < 100) {
print $i * $i . "\n";
$i++;
}
?>
This prints perfect squares below 100. The update $i++ is what allows the loop to finish.
Do While Loops
A do while loop checks its condition after the loop body. That means the body always runs at least once.
<?php
$attempt = 1;
do {
print "Running attempt " . $attempt . "\n";
$attempt++;
} while ($attempt <= 3);
?>
The structure is:
do {
statements
} while (condition);
Use a do while loop when the first pass should happen before the condition decides whether another pass is needed.
The same lookup idea from the while example can be written with do while, but there is a practical warning: because the body runs once before the condition is checked, the array must have at least one element, or you need a guard condition before the loop.
<?php
$names = array("Mira Lane", "Oskar Reed", "Lea Stone", "Ivan Moss");
$numbers = array(310, 455, 612, 208);
$searchName = "Oskar Reed";
$found = "no";
$position = 0;
do {
if ($names[$position] == $searchName) {
$found = "yes";
} else {
$position++;
}
} while ($position < 4 && $found == "no");
if ($found == "yes") {
print $searchName . " has number " . $numbers[$position];
} else {
print $searchName . " was not found";
}
?>
In many scripts, while and do while can solve similar problems. Choose based on whether the loop body should be allowed to run zero times or must run at least once.
Include and Require
The include and require statements load another PHP file and evaluate it as part of the current script.
This is useful when several pages need the same setup, variables, helper functions, or common output.
Imagine a file named profile_data.php:
<?php
$firstName = "Jonas";
$lastName = "Berg";
?>
Another script can include it:
<?php
include "profile_data.php";
print "User: " . $firstName . " " . $lastName;
?>
The result is the same as if the assignments from profile_data.php had been written directly in the second file before the print statement.
The difference between include and require is what happens when the file cannot be loaded:
| Statement | If the file cannot be loaded |
|---|---|
include |
A warning is generated, and the script continues |
require |
Script execution terminates |
For essential files, require is usually the safer choice because continuing without the required setup can create confusing errors later.
<?php
require "app_settings.php";
require "shared_messages.php";
print "Application ready";
?>
PHP also provides include_once and require_once. They load the file only if it has not already been included. This can help when the same shared file might be reached through more than one path in a larger script.
Building a Small Script Step by Step
The following example combines assignments, expressions, conditions, loops, and output. The script calculates a total for a small order and applies a simple discount rule.
<?php
$productNames = array("Keyboard", "Mouse", "Cable");
$productPrices = array(45, 25, 10);
$productQuantities = array(1, 2, 3);
$total = 0;
for ($i = 0; $i < 3; $i++) {
$lineTotal = $productPrices[$i] * $productQuantities[$i];
$total += $lineTotal;
print $productNames[$i] . ": " . $lineTotal . "\n";
}
if ($total >= 100) {
$discount = 10;
} elseif ($total >= 75) {
$discount = 5;
} else {
$discount = 0;
}
$amountToPay = $total - $discount;
print "Total before discount: " . $total . "\n";
print "Discount: " . $discount . "\n";
print "Amount to pay: " . $amountToPay . "\n";
?>
Output:
Keyboard: 45
Mouse: 50
Cable: 30
Total before discount: 125
Discount: 10
Amount to pay: 115
This is still a small example, but it shows the pattern used in larger scripts:
- Store input values.
- Use a loop to process repeated data.
- Use arithmetic expressions to calculate results.
- Use conditions to decide business rules.
- Print the final output.
Common Mistakes to Watch For
Using = instead of ==
Assignment and comparison are different operations.
<?php
$status = "open";
if ($status == "open") {
print "Ticket can be edited";
}
?>
Use == in a condition when you want to test a value.
Forgetting break in a Switch
A switch does not automatically stop at the next case.
<?php
$level = "basic";
switch ($level) {
case "basic":
print "Basic plan";
break;
case "premium":
print "Premium plan";
break;
}
?>
Add break unless you deliberately want execution to continue into the next case.
Creating an Infinite While Loop
If a loop condition never changes, the loop does not stop.
<?php
$i = 0;
while ($i < 3) {
print $i . "\n";
$i++;
}
?>
The update inside the loop is not optional. It is what moves the script toward termination.
Printing Boolean Values Directly
Printing FALSE produces an empty string. This can make the output look broken.
<?php
$paid = FALSE;
print $paid ? "paid" : "not paid";
?>
This style creates readable output instead of relying on PHP's default boolean printing behavior.
Making Conditions Too Clever
This works, but it is harder to read:
<?php
if ($amount && $approved && !$cancelled) {
print "Continue";
}
?>
When the meaning matters, make the comparisons explicit:
<?php
if ($amount > 0 && $approved == TRUE && $cancelled == FALSE) {
print "Continue";
}
?>
Readable conditions reduce bugs.
Practical Checklist
Use this checklist when writing beginner PHP scripts:
- Use one statement per line unless the statement is very short.
- End normal statements with semicolons.
- Use braces for
if,elseif,else, loops, and switch cases with multiple statements. - Use
==for comparison and=for assignment. - Add parentheses around complex arithmetic and logical expressions.
- Prefer
forwhen counting is the main loop pattern. - Prefer
whilewhen the loop stops because a condition changes. - Prefer
do whileonly when the body must run at least once. - Add
breakinside eachswitchcase unless fall-through is intentional. - Use
requirefor files that are essential to the script. - Use
includefor files that are optional enough for the script to continue without them. - Convert logical values to user-friendly text before printing them.
Conclusion
PHP statements are small on their own, but they become powerful when combined. Assignments store state, expressions calculate values, print sends results to the browser, conditions choose between alternatives, loops repeat work, and include or require statements let you reuse files.
A good beginner PHP script is not about using every feature. It is about making each step clear: set values, calculate, decide, repeat when needed, and output the result. Once those habits are in place, larger PHP programs become much easier to read, test, and maintain.