Skip to content

PHP Tutorial Arrays

Common Array Functions

Lesson 131 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

Here is a tour of array functions you will reach for often.

array_merge(): join arrays

index.php
PHP
<?php
$a = ["php", "sql"];
$b = ["css", "js"];

echo implode(", ", array_merge($a, $b));
Output
OUTPUT
php, sql, css, js

array_slice(): take a part

index.php
PHP
<?php
$letters = ["a", "b", "c", "d", "e"];

echo implode(", ", array_slice($letters, 1, 3)) . "\n";   // 3 items from position 1
echo implode(", ", array_slice($letters, -2));            // last 2
Output
OUTPUT
b, c, d
d, e

array_slice() returns a new array and leaves the original alone. (array_splice() changes the original.)

array_unique(): remove duplicates

index.php
PHP
<?php
$tags = ["php", "web", "php", "css", "web"];

echo implode(", ", array_unique($tags));
Output
OUTPUT
php, web, css

array_chunk(): split into groups

Perfect for grids and pages.

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

foreach (array_chunk($items, 3) as $row) {
    echo implode(" ", $row) . "\n";
}
Output
OUTPUT
1 2 3
4 5 6
7

array_diff() and array_intersect()

index.php
PHP
<?php
$all = ["a", "b", "c", "d"];
$owned = ["b", "d"];

echo implode(", ", array_diff($all, $owned)) . "\n";       // in $all but not in $owned
echo implode(", ", array_intersect($all, $owned));          // in both
Output
OUTPUT
a, c
b, d

range(): make a sequence

index.php
PHP
<?php
echo implode(" ", range(1, 5)) . "\n";
echo implode(" ", range(0, 20, 5)) . "\n";
echo implode(" ", range("a", "e"));
Output
OUTPUT
1 2 3 4 5
0 5 10 15 20
a b c d e

array_reverse() and array_sum()

index.php
PHP
<?php
$numbers = [1, 2, 3];

echo implode(", ", array_reverse($numbers)) . "\n";
echo array_sum($numbers) . "\n";
echo array_product($numbers);
Output
OUTPUT
3, 2, 1
6
6

compact() and extract()

compact() builds an array from variables, using their names as keys.

index.php
PHP
<?php
$name = "Isha";
$city = "Kochi";

print_r(compact("name", "city"));
Output
OUTPUT
Array
(
    [name] => Isha
    [city] => Kochi
)

extract() does the opposite, but it creates variables from keys, which can overwrite existing ones. Avoid it for anything that comes from users.

array_walk(), array_key_exists() and more

You have met these in earlier lessons. The full list is long, so the most useful habit is to search the PHP manual before writing your own loop. There is often a function for it.

NeedFunction
Is a value in the listin_array()
Position of a valuearray_search()
Add / remove endsarray_push(), array_pop(), array_shift(), array_unshift()
Transformarray_map()
Filterarray_filter()
Combine to one valuearray_reduce()
Sortsort(), usort(), ksort()
lightbulb
The manual is excellent
The page php.net/manual/en/ref.array.php lists every array function with examples.