Web Development courseLesson 4 of 20 · tap to see all lessons
Web Development · Beginner
PHP Fundamentals: Syntax, Variables, Operators, Control Structures, Functions, and Arrays
Write server-side PHP: variables and data types, operators, if and loops, functions, indexed and associative arrays, and embedding PHP in HTML pages.
- Qyubie Learn Editorial Team
- Published
- 14 min read
Includes 2 quick checks you can do right here.
The pages from the last two lessons are static: every visitor gets exactly the same file. Most of the Web is dynamic: your grades page shows your grades, a shop shows today's prices. That means running code on the server to build the page before it's sent. PHP is a language made for exactly this, and it still powers a large share of the Web, including WordPress and Facebook's early versions.
By the end of this lesson you will be able to:
- set up PHP locally and run a PHP page,
- use variables, data types, and operators,
- write conditions, loops, and functions,
- work with indexed and associative arrays, and
- embed PHP in HTML to produce dynamic content.
How PHP works
PHP runs on the server, not in the browser. When a browser requests profile.php:
- The web server sees the
.phpextension and passes the file to PHP. - PHP runs the code between
<?phpand?>, which may read a database, check the time, and so on. - What the code prints (with
echo) becomes part of the page. - The server sends the finished HTML. The browser never sees the PHP code itself; "View Source" shows only the result.
Setting up. Install XAMPP (it bundles the Apache web server, PHP, and MySQL/MariaDB), start Apache in the XAMPP Control Panel, and save your files in C:\xampp\htdocs\. A file saved as C:\xampp\htdocs\cs324\hello.php opens at http://localhost/cs324/hello.php. Opening the file directly (file:///...) won't work, because then no server runs the PHP.
You can also run a script in a terminal with php hello.php, or start PHP's built-in server in a folder with php -S localhost:8000.
Syntax and output
<?php
// A single-line comment
# Also a comment
/* A multi-line
comment */
echo "Hello, BISU!\n";
echo "PHP version 8", "\n"; // echo can print several values
print "Printed with print\n";Output:
Hello, BISU!
PHP version 8
Printed with print- PHP code starts with
<?php. In a file that contains only PHP, leave out the closing?>; it avoids accidental blank output at the end. - Statements end with a semicolon. A missing one is the most common error.
echoprints text."\n"is a newline in the output; in a browser, use<br>or HTML elements for line breaks instead.
Variables and data types
Variables start with $. You don't declare a type; PHP works it out from the value.
<?php
$name = "Ana Reyes"; // string
$age = 20; // int
$gwa = 1.75; // float
$enrolled = true; // bool
$middleName = null; // null: no value
echo "Name: $name\n"; // variables work inside double quotes
echo 'Name: $name' . "\n"; // ...but not inside single quotes
echo "Age next year: " . ($age + 1) . "\n"; // . joins strings
echo gettype($gwa), "\n";
var_dump($enrolled);
var_dump($middleName);Output:
Name: Ana Reyes
Name: $name
Age next year: 21
double
bool(true)
NULL- Variable names are case-sensitive:
$nameand$Nameare different. Use camelCase or snake_case consistently. .joins strings (Java and JavaScript use+).- Double quotes replace variables with their values; single quotes print exactly what's written.
var_dump()shows a value's type and contents, which makes it the best tool for debugging. (gettypecalls floats"double"for historical reasons.)- Constants have no
$:const PASSING = 75;ordefine("SCHOOL", "BISU");.
PHP converts types automatically when it needs to. "5" + 3 is 8. That's convenient but can surprise you, which is why comparisons need care (below).
Operators
<?php
$a = 17;
$b = 5;
echo $a + $b, " ", $a - $b, " ", $a * $b, "\n";
echo $a / $b, "\n"; // / always gives the exact result
echo intdiv($a, $b), " ", $a % $b, "\n"; // whole division and remainder
echo 2 ** 10, "\n"; // power
$count = 10;
$count += 5;
$count++;
echo $count, "\n";
$text = "Score: ";
$text .= 95; // append
echo $text, "\n";
var_dump(5 == "5"); // equal value (after type conversion)
var_dump(5 === "5"); // identical: same value AND same type
var_dump(5 != 6 && !false);
echo 7 <=> 3, "\n"; // spaceship: -1, 0, or 1
echo $undefinedName ?? "Guest", "\n"; // null coalescing: a fallbackOutput:
22 12 85
3.4
3 2
1024
16
Score: 95
bool(true)
bool(false)
bool(true)
1
Guest- Prefer
===and!==: they compare type as well as value, so0 === "0"isfalse. Loose==causes subtle bugs. ??gives a fallback when a value is missing ornull. You'll use it constantly with form data:$_GET["page"] ?? 1.&&,||, and!are and, or, and not.
Quick check
Conditional statements
<?php
$grade = 87;
if ($grade >= 90) {
$remark = "Excellent";
} elseif ($grade >= 75) {
$remark = "Passed";
} else {
$remark = "Failed";
}
echo "$grade: $remark\n";
$day = "Sat";
switch ($day) {
case "Sat":
case "Sun":
echo "Weekend\n";
break;
default:
echo "Class day\n";
}
// match (PHP 8): returns a value, compares with ===, no break needed
$course = "BSCS";
$college = match ($course) {
"BSCS", "BSIT" => "College of Sciences",
"BSEd" => "College of Teacher Education",
default => "Unknown",
};
echo $college, "\n";Output:
87: Passed
Weekend
College of SciencesPHP writes elseif as one word (else if also works). match is a shorter, stricter switch that returns a value.
Loops
<?php
for ($i = 1; $i <= 3; $i++) {
echo "Row $i\n";
}
$n = 1;
while ($n < 100) {
$n *= 3;
}
echo "First power of 3 at or above 100: $n\n";
$subjects = ["CS 324", "CS 325", "GE 7"];
foreach ($subjects as $subject) {
echo "- $subject\n";
}
foreach ($subjects as $index => $subject) {
echo "$index: $subject\n";
}Output:
Row 1
Row 2
Row 3
First power of 3 at or above 100: 243
- CS 324
- CS 325
- GE 7
0: CS 324
1: CS 325
2: GE 7for, while, and do...while work like Java's. foreach is the one you'll use most: it goes through every element of an array, optionally with its key. break and continue work as usual.
Functions
<?php
function average(array $scores): float {
return array_sum($scores) / count($scores);
}
function greet(string $name, string $greeting = "Hello"): string {
return "$greeting, $name!";
}
function remark(float $grade): string {
return $grade >= 75 ? "Passed" : "Failed";
}
$quiz = [85, 92, 78];
$avg = average($quiz);
echo round($avg, 2), " ", remark($avg), "\n";
echo greet("Ana"), "\n";
echo greet("Ben", "Maayong buntag"), "\n";
echo greet(greeting: "Hi", name: "Cara"), "\n"; // named arguments (PHP 8)Output:
85 Passed
Hello, Ana!
Maayong buntag, Ben!
Hi, Cara!function name(type $param): returnType { ... }. The type declarations are optional but catch mistakes early; use them.$greeting = "Hello"is a default value, used when the caller leaves the argument out.- Variables inside a function are local: a function can't see variables from outside unless they're passed in as parameters.
- PHP has thousands of built-in functions:
strlen,strtoupper,str_replace,round,number_format,date,count, and many more. The PHP Manual documents each one.
Arrays
PHP has one array type that works both as a list and as a map of keys to values.
Indexed arrays use numeric keys from 0:
<?php
$fruits = ["mango", "banana"];
$fruits[] = "pineapple"; // add to the end
echo $fruits[0], "\n";
echo count($fruits), "\n";
sort($fruits);
echo implode(", ", $fruits), "\n"; // join into one string
echo in_array("banana", $fruits) ? "has banana\n" : "no banana\n";Output:
mango
3
banana, mango, pineapple
has bananaAssociative arrays use named keys, like a Java HashMap:
<?php
$student = [
"name" => "Ana Reyes",
"course" => "BSCS",
"year" => 3,
];
echo $student["name"], " (", $student["course"], ")\n";
$student["gwa"] = 1.75; // add a key
foreach ($student as $key => $value) {
echo "$key: $value\n";
}
echo isset($student["email"]) ? "has email\n" : "no email\n";Output:
Ana Reyes (BSCS)
name: Ana Reyes
course: BSCS
year: 3
gwa: 1.75
no emailArrays of arrays hold records, the same shape you'll get from a database query in lesson 8:
<?php
$students = [
["name" => "Ana", "grade" => 92],
["name" => "Ben", "grade" => 74],
["name" => "Cara", "grade" => 85],
];
$passed = array_filter($students, fn($s) => $s["grade"] >= 75);
$names = array_map(fn($s) => $s["name"], $passed);
echo "Passed: ", implode(", ", $names), "\n";
usort($students, fn($a, $b) => $b["grade"] <=> $a["grade"]);
echo "Top: ", $students[0]["name"], "\n";Output:
Passed: Ana, Cara
Top: Anafn($s) => ... is a short arrow function. array_filter keeps the items for which it returns true, array_map transforms each item, and usort sorts with a comparison function.
Quick check
Embedding PHP in HTML
The real power of PHP is mixing it into HTML. Everything outside <?php ... ?> is sent as it is; everything inside runs first.
<?php
$title = "BSCS 3A Class List";
$students = [
["name" => "Ana Reyes", "grade" => 92],
["name" => "Ben Cruz", "grade" => 74],
];
?>
<h1><?= htmlspecialchars($title) ?></h1>
<table>
<tr><th>Name</th><th>Grade</th><th>Remark</th></tr>
<?php foreach ($students as $s): ?>
<tr>
<td><?= htmlspecialchars($s["name"]) ?></td>
<td><?= $s["grade"] ?></td>
<td><?= $s["grade"] >= 75 ? "Passed" : "Failed" ?></td>
</tr>
<?php endforeach; ?>
</table>
<p><?= count($students) ?> students listed.</p>The browser receives plain HTML:
<h1>BSCS 3A Class List</h1>
<table>
<tr><th>Name</th><th>Grade</th><th>Remark</th></tr>
<tr>
<td>Ana Reyes</td>
<td>92</td>
<td>Passed</td>
</tr>
<tr>
<td>Ben Cruz</td>
<td>74</td>
<td>Failed</td>
</tr>
</table>
<p>2 students listed.</p><?= ... ?>is short for<?php echo ... ?>. It's the usual way to print a value into HTML.- The alternative syntax
foreach (...):…endforeach;(alsoif:…endif;) reads better between HTML tags than curly braces. htmlspecialchars()turns characters like<and"into safe codes. Always use it when printing text that might come from users, or someone could inject their own HTML and scripts into your page (more in lesson 5).
Reusing parts of a page. Most sites share a header and footer. Put them in their own files and pull them in:
<?php require "partials/header.php"; ?>
<main>
<h1>About us</h1>
</main>
<?php require "partials/footer.php"; ?>require stops with an error if the file is missing; include only warns. Use require_once for files that define functions, so they're never loaded twice.
Common mistakes
- A missing semicolon, giving syntax error, unexpected ... on the next line.
- Forgetting
$before a variable name. - Using
+to join strings. PHP uses.. - Variables inside single quotes, which print literally.
==where you meant===.- Opening a
.phpfile directly instead of throughhttp://localhost/..., so the code isn't run. - Printing user input without
htmlspecialchars().
Summary
- PHP runs on the server; what it
echoes becomes the page. Code lives in<?php ... ?>, and statements end with;. - Variables start with
$; types arestring,int,float,bool,array,null. Join strings with.; compare with===. if/elseif/else,switch, andmatchchoose;for,while, andforeachrepeat.- Functions take typed parameters with optional defaults and
returna value. - Arrays are lists (
$a[0]) or key-value maps ($a["name"]); arrays of arrays hold records. <?= ?>prints into HTML; escape user text withhtmlspecialchars().
Next lesson: PHP forms and Git/GitHub: handling GET and POST, validating input, and putting your code under version control.