MasterPHP.in
PHP Tutorial

PHP Array Functions & Operations


Why PHP's Built-In Array Functions Matter

PHP ships with well over a hundred built-in functions for working with arrays, which is one of the language's biggest strengths for handling data efficiently. Rather than manually writing loops for every operation, you can lean on functions that are already optimized, tested, and instantly recognizable to other PHP developers. This lesson walks through the array functions you'll reach for most often, grouped by what they actually do.


Counting and Inspecting Arrays


php

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

echo count($fruits);          // 3 - number of elements
var_dump(empty($fruits));     // false - array has elements
var_dump(in_array("Mango", $fruits)); // true - checks if a value exists
echo array_search("Banana", $fruits); // 1 - returns the key/index of a value

in_array() checks whether a value exists anywhere in the array and returns a boolean, while array_search() goes a step further and tells you exactly where that value is located, returning its key. If the value isn't found, array_search() returns false, so as with strpos(), it's safest to compare the result using strict comparison (===).


Adding and Removing Elements


php

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

array_push($fruits, "Mango");     // adds to the end
print_r($fruits); // ["Apple", "Banana", "Mango"]

array_pop($fruits);               // removes the last element
print_r($fruits); // ["Apple", "Banana"]

array_unshift($fruits, "Grapes"); // adds to the beginning
print_r($fruits); // ["Grapes", "Apple", "Banana"]

array_shift($fruits);             // removes the first element
print_r($fruits); // ["Apple", "Banana"]

A quicker shorthand for adding a single item to the end of an array is simply $fruits[] = "Mango";, which many PHP developers use instead of array_push() for single insertions.


Merging and Combining Arrays


php

<?php
$vegetables = ["Carrot", "Potato"];
$fruits = ["Apple", "Banana"];

$combined = array_merge($vegetables, $fruits);
print_r($combined); // ["Carrot", "Potato", "Apple", "Banana"]

// Combining separate key and value arrays into one associative array
$keys = ["name", "age", "city"];
$values = ["Rohan", 28, "Mumbai"];

$user = array_combine($keys, $values);
print_r($user); // ["name" => "Rohan", "age" => 28, "city" => "Mumbai"]

With array_merge(), it's worth knowing that numeric keys get renumbered, while string keys with the same name in both arrays will have the later array's value overwrite the earlier one.


Extracting Keys and Values


php

<?php
$user = ["name" => "Rohan", "age" => 28, "city" => "Mumbai"];

print_r(array_keys($user));    // ["name", "age", "city"]
print_r(array_values($user));  // ["Rohan", 28, "Mumbai"]
var_dump(array_key_exists("age", $user)); // true

array_key_exists() is subtly different from checking isset($user['age'])array_key_exists() returns true even if the value is null, while isset() would return false in that case, since isset() treats null values as "not set."


Slicing and Splicing Arrays


php

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

$sliced = array_slice($numbers, 1, 3);
print_r($sliced); // [20, 30, 40] - extracts a portion, original unchanged

array_splice($numbers, 1, 2, ["X", "Y"]);
print_r($numbers); // [10, "X", "Y", 40, 50] - removes and replaces, modifies original

The key difference: array_slice() extracts a copy without touching the original array, while array_splice() directly modifies the original array by removing and optionally inserting new elements.


Transforming Arrays: map, filter, reduce

These three functions are the backbone of working with data cleanly, and are widely used in real applications.


php

<?php
$prices = [100, 250, 400];

// array_map: transforms every element
$withTax = array_map(function ($price) {
    return $price * 1.18; // adding 18% tax
}, $prices);
print_r($withTax); // [118, 295, 472]

// array_filter: keeps only elements matching a condition
$expensive = array_filter($prices, function ($price) {
    return $price > 150;
});
print_r($expensive); // [250, 400] (keys preserved: 1, 2)

// array_reduce: collapses an array into a single value
$total = array_reduce($prices, function ($carry, $price) {
    return $carry + $price;
}, 0);
echo $total; // 750

array_reduce() is the least intuitive of the three at first: the $carry parameter accumulates a running result across each element, starting from the initial value provided as the third argument (0 in this example).


Sorting Arrays

PHP provides different sorting functions depending on whether you're working with an indexed array, an associative array, and whether you want to preserve key relationships.


php

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

sort($numbers);          // ascending, re-indexes keys
print_r($numbers); // [10, 20, 30, 50]

rsort($numbers);         // descending, re-indexes keys
print_r($numbers); // [50, 30, 20, 10]

$ages = ["Rohan" => 28, "Priya" => 24, "Aman" => 32];

asort($ages);            // sort by value, keep keys
print_r($ages); // ["Priya" => 24, "Rohan" => 28, "Aman" => 32]

ksort($ages);            // sort by key, keep values
print_r($ages); // ["Aman" => 32, "Priya" => 24, "Rohan" => 28]


Function     Sorts By        Keeps Original Keys?
------------------------------------------------------------
sort()        Value           No (re-indexes)
rsort()       Value (desc)    No (re-indexes)
asort()       Value           Yes
arsort()      Value (desc)    Yes
ksort()       Key             Yes (obviously, sorting is by key)
krsort()      Key (desc)      Yes

Removing Duplicates and Reversing


php

<?php
$numbers = [1, 2, 2, 3, 3, 3, 4];

$unique = array_unique($numbers);
print_r($unique); // [1, 2, 3, 4] (keys from original positions preserved)

$reversed = array_reverse($numbers);
print_r($reversed); // [4, 3, 3, 3, 2, 2, 1]

Comparing Arrays: diff and intersect


php

<?php
$currentUsers = ["Rohan", "Priya", "Aman"];
$previousUsers = ["Priya", "Aman", "Sara"];

$newUsers = array_diff($currentUsers, $previousUsers);
print_r($newUsers); // ["Rohan"] - present in current, not in previous

$returningUsers = array_intersect($currentUsers, $previousUsers);
print_r($returningUsers); // ["Priya", "Aman"] - present in both

These two functions are especially useful for comparison tasks — finding newly added items, identifying what's missing, or determining overlap between two data sets.


Splitting Arrays into Chunks


php

<?php
$items = [1, 2, 3, 4, 5, 6, 7];

$chunks = array_chunk($items, 3);
print_r($chunks);
// [[1, 2, 3], [4, 5, 6], [7]]

array_chunk() is commonly used for pagination or displaying items in a grid layout, where you need to break a long list into fixed-size groups.


Checking if an Array is Empty


php

<?php
$cart = [];

if (empty($cart)) {
    echo "Your cart is empty.";
}

// Equivalent alternative
if (count($cart) === 0) {
    echo "Your cart is empty.";
}

Both approaches work, but empty() is generally considered slightly more readable and doesn't require calling a function to count elements first.


Quick Reference: Function Categories


Category          Common Functions
------------------------------------------------------------
Inspecting         count(), in_array(), array_search()
Adding/Removing    array_push(), array_pop(), array_shift(),
                   array_unshift()
Merging            array_merge(), array_combine()
Keys & Values      array_keys(), array_values(), array_key_exists()
Extracting         array_slice(), array_splice()
Transforming       array_map(), array_filter(), array_reduce()
Sorting            sort(), rsort(), asort(), ksort()
Cleaning           array_unique(), array_reverse()
Comparing          array_diff(), array_intersect()
Grouping           array_chunk()


What's Next

With a solid toolkit of array functions, you're ready to see how these functions come together to solve real, practical problems — from building shopping carts to processing form data — which is exactly what the next lesson covers.

Frequently Asked Questions

array_slice() extracts a portion of an array and returns it as a new array, leaving the original array unchanged. array_splice() directly modifies the original array by removing elements and optionally inserting replacements at that position.
array_map() is ideal when you want to transform every element in an array and get a new array back, and it communicates that intent clearly in one line. A foreach loop is more flexible when you need to do more complex logic, like conditionally skipping items or modifying multiple variables at once.
array_key_exists() returns true as long as the key exists in the array, even if its value is null. isset() returns false in that same situation, because it specifically checks for both existence and a non-null value.
Yes. Functions like sort(), rsort(), asort(), and ksort() all modify the array they're given directly, rather than returning a new sorted copy. If you need to keep the original order intact, make a copy of the array before sorting.
The carry parameter holds the accumulated result as array_reduce() processes each element in the array, one at a time. It starts at the initial value you provide as the third argument, and is updated and passed forward with each step until the final result is returned.

Share this tutorial