Learn PHP from Scratch

PHP Functions and Arrays

Lesson 4 of 7 2 min read Updated 10 October 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.

Practice tasks

Reading is not enough. Try these without copying code, then compare with the lesson.

  • Write a function that returns the average of an array.
  • Create an associative array of students and marks and print it.
  • Use sort, count and in_array.

Common mistakes

  • Forgetting that a function cannot see global variables by default.
  • Using the wrong key name in an associative array.

Quick check

What is an associative array?

An array with named keys.

How do you give a parameter a default value?

Give the parameter a default in the function signature.