Learn PHP from Scratch

PHP Functions and Arrays

Lesson 4 of 7 2 min read Updated 28 September 2026

Functions

<?php
function greet(string $name = "Guest"): string {
    return "Hello, $name!";
}
echo greet("Asha");
echo greet();
  • Type declarations (string, int) make code safer.
  • Default values make parameters optional.

Arrays

$fruits = ["mango", "banana", "apple"];      // indexed
echo $fruits[0];
$fruits[] = "orange";                         // append
echo count($fruits);

$student = [                                  // associative
    "name" => "Asha",
    "age" => 20,
    "city" => "Karad",
];
echo $student["name"];

Looping through arrays

foreach ($student as $key => $value) {
    echo "$key: $value<br>";
}

Multidimensional arrays

$students = [
    ["name" => "Asha", "marks" => 88],
    ["name" => "Ravi", "marks" => 72],
];
foreach ($students as $s) {
    echo $s["name"] . " scored " . $s["marks"] . "<br>";
}

Useful array functions

$nums = [5, 3, 8, 1];
sort($nums);                          // 1, 3, 5, 8
echo array_sum($nums);                // 17
echo max($nums) . " " . min($nums);
in_array(3, $nums);                   // true
array_map(fn($n) => $n * 2, $nums);   // double each
array_filter($nums, fn($n) => $n > 3);
implode(", ", $nums);                 // "1, 3, 5, 8"
explode(",", "a,b,c");                // ["a", "b", "c"]

Practice

Write a function that takes an array of marks and returns the average and the highest mark as an associative array.