PHP - PHP Array Functions and Advanced Array Operations

Arrays are one of the most important data structures in PHP. They allow developers to store multiple values in a single variable and organize data using keys and values. PHP provides a large collection of built-in array functions that make it easier to create, modify, search, filter, sort, combine, and process arrays.

Understanding these functions is especially useful when working with database results, form data, API responses, configuration data, and collections of records.

1. Creating an Array

A PHP array can contain multiple values.

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

Each value is automatically assigned an integer index starting from 0.

echo $fruits[0];

Output:

Apple

Associative arrays use named keys.

$student = [
    "name" => "Rahul",
    "age" => 21,
    "course" => "PHP"
];

Values can be accessed using their keys.

echo $student["name"];

Output:

Rahul

2. Counting Array Elements

The count() function determines how many elements an array contains.

$subjects = ["PHP", "Java", "Python", "SQL"];

echo count($subjects);

Output:

4

This is commonly used when processing arrays with loops or validating whether an array contains a particular number of elements.

For example:

if (count($subjects) > 0) {
    echo "Subjects are available.";
}

3. Adding Elements to an Array

The array_push() function adds one or more elements to the end of an array.

$fruits = ["Apple", "Banana"];

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

print_r($fruits);

The resulting array contains:

Apple
Banana
Orange
Mango

For a single value, PHP also allows a simpler approach:

$fruits[] = "Orange";

This is generally convenient when only one element needs to be added.

4. Removing Elements

The array_pop() function removes the last element.

$fruits = ["Apple", "Banana", "Orange"];

$removed = array_pop($fruits);

echo $removed;

Output:

Orange

The array_shift() function removes the first element.

$fruits = ["Apple", "Banana", "Orange"];

$removed = array_shift($fruits);

echo $removed;

Output:

Apple

These functions are useful when implementing stack-like or queue-like operations.

5. Searching for Values

The in_array() function checks whether a particular value exists in an array.

$fruits = ["Apple", "Banana", "Orange"];

if (in_array("Banana", $fruits)) {
    echo "Banana is available.";
}

Output:

Banana is available.

For stricter comparison, the third parameter can be set to true.

in_array(10, $numbers, true);

Strict comparison checks both the value and its data type.

6. Finding an Array Key

The array_search() function searches for a value and returns its corresponding key.

$fruits = ["Apple", "Banana", "Orange"];

$key = array_search("Banana", $fruits);

echo $key;

Output:

1

For associative arrays:

$students = [
    "student1" => "Rahul",
    "student2" => "Anita"
];

$key = array_search("Anita", $students);

echo $key;

Output:

student2

It is important to check the result carefully because array_search() can return 0, which is a valid key but can evaluate as false in a simple conditional.

7. Filtering Arrays with array_filter()

array_filter() creates a new array containing only the elements that satisfy a condition.

Consider:

$numbers = [10, 15, 20, 25, 30];

We can filter only even numbers:

$evenNumbers = array_filter($numbers, function ($number) {
    return $number % 2 === 0;
});

print_r($evenNumbers);

The resulting values are:

10
20
30

array_filter() is particularly useful when processing large collections of data.

For example, filtering students whose marks are above 50:

$marks = [45, 67, 82, 39, 91];

$passed = array_filter($marks, function ($mark) {
    return $mark >= 50;
});

print_r($passed);

8. Transforming Arrays with array_map()

The array_map() function applies a function to every element of an array.

For example:

$numbers = [1, 2, 3, 4];

$squares = array_map(function ($number) {
    return $number * $number;
}, $numbers);

print_r($squares);

Result:

1
4
9
16

Unlike array_filter(), which selects particular elements, array_map() transforms the elements.

A common practical example is converting names to uppercase:

$names = ["rahul", "anita", "vijay"];

$uppercaseNames = array_map("strtoupper", $names);

print_r($uppercaseNames);

9. Reducing an Array with array_reduce()

array_reduce() processes all elements and combines them into a single result.

For example, calculating the total:

$prices = [100, 200, 300, 400];

$total = array_reduce($prices, function ($carry, $price) {
    return $carry + $price;
}, 0);

echo $total;

Output:

1000

Here:

  • $carry stores the accumulated result.

  • $price represents the current array element.

  • 0 is the initial value.

Another example is calculating a product:

$numbers = [2, 3, 4];

$product = array_reduce($numbers, function ($carry, $number) {
    return $carry * $number;
}, 1);

echo $product;

Output:

24

10. Processing Arrays with array_walk()

array_walk() applies a callback function to each element.

$names = ["Rahul", "Anita", "Vijay"];

array_walk($names, function ($name) {
    echo $name . "<br>";
});

This is useful when you need to perform an operation on every element without necessarily creating a new array.

The callback can also receive the key:

$students = [
    "s1" => "Rahul",
    "s2" => "Anita"
];

array_walk($students, function ($name, $id) {
    echo $id . ": " . $name . "<br>";
});

11. Sorting Arrays

PHP provides several functions for sorting arrays.

sort() sorts an indexed array in ascending order.

$numbers = [40, 10, 30, 20];

sort($numbers);

print_r($numbers);

Result:

10
20
30
40

rsort() sorts in descending order.

rsort($numbers);

For associative arrays, asort() sorts values while preserving their keys.

$marks = [
    "Rahul" => 80,
    "Anita" => 95,
    "Vijay" => 70
];

asort($marks);

ksort() sorts an associative array according to its keys.

ksort($marks);

Understanding the difference between sorting by values and sorting by keys is important when working with associative data.

12. Combining Arrays

The array_merge() function combines two or more arrays.

$first = ["Apple", "Banana"];
$second = ["Orange", "Mango"];

$result = array_merge($first, $second);

print_r($result);

Result:

Apple
Banana
Orange
Mango

For numeric-indexed arrays, the indexes are re-created sequentially.

Associative arrays can also be merged:

$studentDetails = [
    "name" => "Rahul"
];

$courseDetails = [
    "course" => "PHP"
];

$result = array_merge($studentDetails, $courseDetails);

The resulting array contains both key-value pairs.

13. Extracting Parts of an Array

array_slice() returns a portion of an array without modifying the original array.

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

$result = array_slice($numbers, 1, 3);

print_r($result);

Result:

20
30
40

The first parameter is the source array, the second is the starting position, and the third specifies the number of elements.

This is useful for pagination and displaying a selected portion of a dataset.

14. Replacing Array Elements

array_splice() can remove and replace elements within an array.

$fruits = ["Apple", "Banana", "Orange"];

array_splice($fruits, 1, 1, ["Mango"]);

print_r($fruits);

The result becomes:

Apple
Mango
Orange

Unlike array_slice(), array_splice() modifies the original array.

15. Removing Duplicate Values

The array_unique() function removes duplicate values.

$numbers = [10, 20, 10, 30, 20];

$uniqueNumbers = array_unique($numbers);

print_r($uniqueNumbers);

The duplicate values are removed.

This can be useful when processing user selections, database results, categories, or tags.

16. Finding Minimum and Maximum Values

The min() and max() functions can be used to find the smallest and largest values.

$marks = [78, 91, 65, 88, 95];

echo min($marks);
echo max($marks);

Output:

65
95

These functions are useful for calculating ranges and identifying extreme values in datasets.

17. Combining Keys and Values

array_combine() creates an array by using one array as keys and another as values.

$subjects = ["Math", "Science", "English"];
$marks = [85, 90, 78];

$result = array_combine($subjects, $marks);

print_r($result);

The resulting structure is conceptually:

Math    => 85
Science => 90
English => 78

This is useful when two related datasets need to be converted into an associative array.

18. Practical Example

Consider an array containing student marks:

$marks = [45, 67, 82, 39, 91, 76];

We can use several array functions together.

First, filter students who passed:

$passed = array_filter($marks, function ($mark) {
    return $mark >= 50;
});

Then calculate the total:

$total = array_reduce($passed, function ($carry, $mark) {
    return $carry + $mark;
}, 0);

Calculate the number of passed students:

$count = count($passed);

Calculate the average:

$average = $total / $count;

This demonstrates how PHP array functions can be combined to perform data-processing operations with relatively little code.

19. Difference Between array_map(), array_filter(), and array_reduce()

These three functions are particularly important.

Function Main Purpose Result
array_map() Transform each element New array
array_filter() Select elements based on a condition Filtered array
array_reduce() Combine elements into one result Single value

For example:

$numbers = [1, 2, 3, 4, 5];

Transform:

array_map(fn($n) => $n * 2, $numbers);

Filter:

array_filter($numbers, fn($n) => $n > 3);

Reduce:

array_reduce($numbers, fn($carry, $n) => $carry + $n, 0);

Learning to distinguish these operations helps developers select the appropriate array function instead of writing unnecessary loops.

20. Importance of Advanced Array Operations

Advanced array operations are important because real-world PHP applications frequently process collections of data. Database queries can return arrays of records, APIs can provide arrays containing structured information, and forms can submit multiple values.

Instead of manually writing complex loops for every operation, PHP's array functions provide reusable tools for:

  • Searching and validating data

  • Filtering unwanted records

  • Transforming data

  • Calculating totals and averages

  • Sorting information

  • Removing duplicates

  • Combining datasets

  • Extracting specific portions of data

  • Processing multidimensional data

  • Preparing data for display or API responses

A strong understanding of PHP arrays and their built-in functions makes code shorter, clearer, and easier to maintain. It also provides a foundation for working with more advanced PHP concepts such as collections, database results, JSON data, and application-level data processing.