Lesson 25 of 50 – PHP Array Functions
50%

PHP Array Functions

PHP provides many built-in array functions to count elements, add or remove values, search arrays, sort data, and combine arrays. These functions make array operations easier and reduce the amount of code we need to write.

1. count() and sizeof()

The count() function returns the number of elements at the top level of an array. sizeof() is an alias of count().

<?php
$fruits = ["Apple", "Mango", "Banana", "Orange"];

echo count($fruits);
echo "<br>";
echo sizeof($fruits);
?>
Output:
4
4

Example with a loop:

<?php
$numbers = [10, 20, 30, 40, 50];

for ($i = 0; $i < count($numbers); $i++) {
    echo $numbers[$i] . "<br>";
}
?>
Output:
10
20
30
40
50

For nested arrays, count() counts only the outer elements by default. You can use COUNT_RECURSIVE to count nested elements as well.

2. array_push() and array_pop()

array_push() adds one or more elements to the end of an array. array_pop() removes and returns the last element.

<?php
$fruits = ["Apple", "Mango"];

array_push($fruits, "Banana", "Orange");

print_r($fruits);
?>
Output:
Array
(
    [0] => Apple
    [1] => Mango
    [2] => Banana
    [3] => Orange
)

Using array_pop():

<?php
$fruits = ["Apple", "Mango", "Banana"];

$removed = array_pop($fruits);

echo "Removed: " . $removed . "<br>";
print_r($fruits);
?>
Output:
Removed: Banana
Array
(
    [0] => Apple
    [1] => Mango
)

You can also append one value using $fruits[] = "Orange";.

3. array_unshift() and array_shift()

array_unshift() adds elements to the beginning of an array. array_shift() removes and returns the first element.

Using array_unshift():

<?php
$numbers = [20, 30, 40];

array_unshift($numbers, 10);

print_r($numbers);
?>
Output:
Array
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
)

Using array_shift():

<?php
$numbers = [10, 20, 30, 40];

$removed = array_shift($numbers);

echo "Removed: " . $removed . "<br>";
print_r($numbers);
?>
Output:
Removed: 10
Array
(
    [0] => 20
    [1] => 30
    [2] => 40
)

These functions reindex the remaining numeric keys in a normal indexed array. String keys are preserved.

4. array_merge() and array_combine()

array_merge() combines arrays. Numeric keys are renumbered, while string keys from later arrays replace matching string keys from earlier arrays.

<?php
$a = ["Apple", "Mango"];
$b = ["Banana", "Orange"];

$result = array_merge($a, $b);

print_r($result);
?>
Output:
Array
(
    [0] => Apple
    [1] => Mango
    [2] => Banana
    [3] => Orange
)

Using array_combine():

array_combine() creates an associative array from one array of keys and another array of corresponding values. Both arrays must have the same number of elements.

<?php
$keys = ["name", "age", "course"];
$values = ["Rahul", 20, "PHP"];

$result = array_combine($keys, $values);

print_r($result);
?>
Output:
Array
(
    [name] => Rahul
    [age] => 20
    [course] => PHP
)
5. array_keys(), array_values(), and array_key_exists()

These functions help you retrieve keys and values and check whether a particular key exists.

<?php
$student = [
    "name" => "Rahul",
    "age" => 20,
    "course" => "PHP"
];

print_r(array_keys($student));
echo "<br>";
print_r(array_values($student));
?>
Output:
Array
(
    [0] => name
    [1] => age
    [2] => course
)
Array
(
    [0] => Rahul
    [1] => 20
    [2] => PHP
)

Check whether a key exists:

<?php
$student = [
    "name" => "Rahul",
    "age" => 20
];

if (array_key_exists("age", $student)) {
    echo "Age key exists";
} else {
    echo "Age key does not exist";
}
?>
Output:
Age key exists

Unlike isset(), array_key_exists() returns true when the key exists even if its value is null.

6. in_array() and array_search()

in_array() checks whether a value exists in an array. array_search() returns the matching key or false if no match is found.

Using in_array():

<?php
$fruits = ["Apple", "Mango", "Banana"];

if (in_array("Mango", $fruits, true)) {
    echo "Mango found";
} else {
    echo "Mango not found";
}
?>
Output:
Mango found

Using array_search():

<?php
$fruits = ["Apple", "Mango", "Banana"];

$key = array_search("Mango", $fruits, true);

if ($key !== false) {
    echo "Mango found at index " . $key;
} else {
    echo "Mango not found";
}
?>
Output:
Mango found at index 1

Use !== false when checking array_search(), because a match may be found at numeric key 0.

7. sort(), rsort(), asort(), and arsort()

PHP provides sorting functions for ascending and descending order. Some preserve array keys, while others reindex numeric keys.

Function Purpose
sort() Ascending order; reindexes numeric keys.
rsort() Descending order; reindexes numeric keys.
asort() Ascending order by value; preserves keys.
arsort() Descending order by value; preserves keys.

Example: sort()

<?php
$numbers = [40, 10, 30, 20];

sort($numbers);

print_r($numbers);
?>
Output:
Array
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
)

Example: asort()

<?php
$marks = [
    "Rahul" => 80,
    "Amit" => 95,
    "Priya" => 85
];

asort($marks);

print_r($marks);
?>
Output:
Array
(
    [Rahul] => 80
    [Priya] => 85
    [Amit] => 95
)

The student names remain associated with their original marks because asort() preserves the keys.

8. array_reverse(), array_unique(), and array_slice()

array_reverse() – Reverse an array

<?php
$numbers = [10, 20, 30, 40];

print_r(array_reverse($numbers));
?>
Output:
Array
(
    [0] => 40
    [1] => 30
    [2] => 20
    [3] => 10
)

array_unique() – Remove duplicate values

<?php
$numbers = [10, 20, 10, 30, 20];

print_r(array_unique($numbers));
?>
Output:
Array
(
    [0] => 10
    [1] => 20
    [3] => 30
)

The original keys are preserved by array_unique().

array_slice() – Extract part of an array

<?php
$numbers = [10, 20, 30, 40, 50];

print_r(array_slice($numbers, 1, 3));
?>
Output:
Array
(
    [0] => 20
    [1] => 30
    [2] => 40
)

By default, array_slice() reindexes numeric keys in the returned result. It does not modify the original array.

9. Practical Example: Calculate Student Results

The following example uses array functions to calculate student totals and averages.

<?php
$students = [
    "Rahul" => [80, 85, 90],
    "Amit" => [75, 88, 92],
    "Priya" => [90, 95, 89]
];

foreach ($students as $name => $marks) {
    $total = array_sum($marks);
    $subjects = count($marks);
    $average = $subjects > 0 ? $total / $subjects : 0;

    echo "Student: " . $name . "<br>";
    echo "Total: " . $total . "<br>";
    echo "Average: " . number_format($average, 2) . "<br>";
    echo "<hr>";
}
?>
Output:
Student: Rahul
Total: 255
Average: 85.00

Student: Amit
Total: 255
Average: 85.00

Student: Priya
Total: 274
Average: 91.33

This example combines array_sum(), count(), and number_format() to generate a simple student report.

Practice Assignments
  1. Count the number of elements in an array using count().
  2. Add three values using array_push() and remove the last value using array_pop().
  3. Add an element at the beginning using array_unshift().
  4. Combine two arrays using array_merge().
  5. Extract keys and values from an associative array.
  6. Search for a value using in_array() and array_search().
  7. Sort five numbers in ascending and descending order.
  8. Remove duplicate values using array_unique().
  9. Calculate the total and average marks of three students.

🧠 Quick Quiz

1. Which function adds elements to the end of an array?




2. Which function sorts an associative array by value while preserving keys?




3. Which function returns the keys of an array?