Functions and Arrays
function greet($name, $greeting = "Hello") {n return "$greeting, $name!";n}nnecho greet("Yash"); // Hello, Yash!necho greet("Yash", "Welcome"); // Welcome, Yash!
Type declarations (recommended)
function greet(string $name, string $greeting = "Hello"): string {n return "$greeting, $name!";n}
Modern PHP supports optional type declarations on parameters and return values — string $name and : string above. These are not required, but adding them lets PHP catch type mismatches automatically and makes a function’s expected inputs and outputs far clearer to anyone reading the code, similar to what Java or C++ require by default.
Indexed arrays
$courses = ["Python", "PHP", "SQL"];n$courses[] = "Java"; // appends to the endnecho $courses[0]; // Pythonnecho count($courses); // 4
Associative arrays
$student = [n "name" => "Yash",n "course" => "PHP",n "completedLessons" => 3,n];necho $student["name"];n$student["completedLessons"]++;
An associative array is PHP’s equivalent of a Python dictionary or a JavaScript object — a set of named keys mapped to values. Unlike Python or JavaScript, PHP uses the exact same array type for both an ordered list and a key-value map; which one you have simply depends on whether you gave it explicit keys.
Useful array functions
$scores = [90, 85, 78, 92];n$total = array_sum($scores);n$doubled = array_map(fn($s) => $s * 2, $scores);n$passing = array_filter($scores, fn($s) => $s >= 80);nsort($scores); // sorts in place, modifying the original array
array_map and array_filter mirror the same ideas as JavaScript’s .map()/.filter() and Python’s list comprehensions — PHP’s built-in array functions cover an enormous amount of everyday data manipulation before you’d ever need a loop written by hand.