Syntax Basics
beginnerPart of PHP Basics
Theory
This lesson covers the core PHP syntax you need to write functional scripts. PHP's syntax is similar to C and Perl, making it familiar to many developers.
Variables
PHP variables start with $ followed by the variable name. They are dynamically typed:
<?php
$name = "Alice"; // String
$age = 25; // Integer
$price = 19.99; // Float
$isActive = true; // Boolean
$colors = ["red", "blue"]; // Array
$nothing = null; // Null
?>Naming rules:
- Must start with a letter or underscore
- Can contain letters, digits, and underscores
- Case-sensitive (
$name≠$Name) - Use
snake_caseby convention
Variable variables — using a variable's value as another variable's name:
<?php
$varName = "city";
$$varName = "New York"; // Creates $city = "New York"
echo $city; // New York
?>Data Types
PHP supports eight primitive data types:
<?php
// Scalar types
$string = "Hello";
$int = 42;
$float = 3.14;
$bool = true;
// Compound types
$array = [1, 2, 3];
$object = new stdClass();
$callable = function() { return "hi"; };
// Special types
$null = null;
?>Type checking and conversion:
<?php
var_dump($value); // Shows type and value
gettype($value); // Returns type as string
is_string($value); // Type checking functions
is_int($value);
is_array($value);
// Type casting
$int = (int) "42"; // 42
$float = (float) "3.14"; // 3.14
$string = (string) 100; // "100"
$bool = (bool) "true"; // true
?>echo vs print
Both output text, but with differences:
<?php
echo "Hello"; // No return value
echo "Hello", " ", "World"; // Accepts multiple arguments
print "Hello"; // Returns 1 (can use in expressions)
print "Hello World"; // Only one argument
// print_r and var_dump for debugging
$arr = [1, 2, 3];
print_r($arr); // Human-readable array
var_dump($arr); // With type information
?>Strings
Single vs double quotes:
<?php
$name = "Alice";
// Single quotes — literal, no variable interpolation
echo 'Hello $name'; // Hello $name
// Double quotes — interpolates variables
echo "Hello $name"; // Hello Alice
// Curly braces for complex expressions
echo "Hello {$name}Smith"; // Hello AliceSmith
// Heredoc (multi-line with interpolation)
echo <<<EOT
Hello $name,
This is a multi-line
string.
EOT;
// Nowdoc (multi-line, no interpolation)
echo <<<'EOT'
This treats $name as literal.
EOT;
?>Common string functions:
<?php
strlen("Hello"); // 5
strtoupper("hello"); // HELLO
strtolower("HELLO"); // hello
ucfirst("hello"); // Hello
ucwords("hello world"); // Hello World
trim(" hi "); // "hi"
str_replace("old", "new", $str);
substr("Hello World", 0, 5); // Hello
strpos("Hello", "ll"); // 2
explode(",", "a,b,c"); // ["a", "b", "c"]
implode(", ", ["a", "b"]); // "a, b"
?>Constants
<?php
// define() — runtime constants
define("SITE_NAME", "My Website");
define("MAX_USERS", 100);
echo SITE_NAME;
// const — compile-time constants (in classes or top-level)
const VERSION = "1.0.0";
echo VERSION;
// Predefined constants
echo PHP_VERSION;
echo PHP_OS;
echo __LINE__;
echo __FILE__;
echo __DIR__;
?>Operators
Arithmetic: +, -, *, /, %, ** (exponentiation)
Comparison: ==, === (identical), !=, !==, <, >, <=, >=, <=> (spaceship)
Logical: && (and), || (or), ! (not), and, or (lower precedence)
String: . (concatenation), .= (concatenating assignment)
Assignment: =, +=, -=, *=, /=, .=
<?php
// Loose vs strict comparison
var_dump(5 == "5"); // true (type coercion)
var_dump(5 === "5"); // false (different types)
// Spaceship operator (returns -1, 0, or 1)
echo 1 <=> 2; // -1
echo 2 <=> 2; // 0
echo 3 <=> 2; // 1
// Null coalescing operator
$username = $_GET['user'] ?? 'guest'; // ?? provides default
// Ternary
$status = $age >= 18 ? "Adult" : "Minor";
?>if/else and switch
<?php
$score = 85;
if ($score >= 90) {
echo "A";
} elseif ($score >= 80) {
echo "B";
} elseif ($score >= 70) {
echo "C";
} else {
echo "F";
}
// Alternative syntax (useful in templates)
if ($score >= 50): ?>
<p>You passed!</p>
<?php endif; ?>
// Switch
$day = "Monday";
switch ($day) {
case "Saturday":
case "Sunday":
echo "Weekend!";
break;
default:
echo "Weekday";
break;
}
?>Loops
<?php
// for
for ($i = 0; $i < 5; $i++) {
echo $i;
}
// while
$i = 0;
while ($i < 5) {
echo $i++;
}
// do-while (always runs at least once)
$i = 0;
do {
echo $i++;
} while ($i < 5);
// foreach (most common for arrays)
$fruits = ["Apple", "Banana", "Cherry"];
foreach ($fruits as $fruit) {
echo $fruit;
}
// foreach with key
$ages = ["Alice" => 25, "Bob" => 30];
foreach ($ages as $name => $age) {
echo "$name is $age";
}
// Alternative syntax (templates)
foreach ($items as $item): ?>
<li><?= $item ?></li>
<?php endforeach; ?>
?>Functions
<?php
// Basic function
function greet($name) {
return "Hello, $name!";
}
echo greet("Alice");
// Default parameters
function multiply($a, $b = 1) {
return $a * $b;
}
echo multiply(5); // 5
echo multiply(5, 3); // 15
// Type declarations
function add(int $a, int $b): int {
return $a + $b;
}
// Strict types (declare at top of file)
declare(strict_types=1);
// Variable scope
$global = "outside";
function test() {
global $global; // Import global
$local = "inside";
echo $global; // "outside"
echo $local; // "inside"
}
// Static variables (persist across calls)
function counter() {
static $count = 0;
return ++$count;
}
echo counter(); // 1
echo counter(); // 2
?>Declare declare(strict_types=1); at the top of your PHP files to enforce strict type checking. This prevents automatic type coercion in function arguments and makes your code more predictable.
Practical Examples
Use foreach instead of for when iterating over arrays. It's cleaner and less error-prone. Use the key => value syntax when you need the array keys.
Exercises
Data Type Explorer
Create a PHP script that declares variables of different types (string, int, float, bool, null, array). Use var_dump() on each and display the type. Then demonstrate type juggling by performing operations between different types.
Expected Output:
Each variable displayed with var_dump showing its type and value, plus examples of implicit and explicit type conversion.FizzBuzz with Loops
Write a PHP script that prints numbers from 1 to 100. For multiples of 3, print 'Fizz' instead of the number. For multiples of 5, print 'Buzz'. For multiples of both, print 'FizzBuzz'.
Expected Output:
1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, ...String Utility Library
Create a set of string utility functions: truncate (crops at word boundary), slugify (URL-friendly), maskEmail (hides part of email), and contains (checks if string contains a substring).
Expected Output:
Hello...\nhello-world-php-is-great\nali***@example.com\nyesMini Quiz
Mini Quiz
Mini Project
Mini Project: Text Analysis Tool
Create a PHP web page that accepts a block of text, analyzes it, and displays statistics: character count, word count, sentence count, average word length, most common words, keyword density, and a readability score.
Requirements:
Bonus Challenge
Add a simple readability score using the Flesch-Kincaid formula. Generate a word cloud using HTML spans with varying font sizes based on frequency.