agyanadda@gmail.com

PHP Array Functions

PHP Arrays 1 min read Updated Dec 1, 2026 Topic 20 of 36

Transform and filter

Function Does
array_map(fn, $arr) change every item, return a new array
array_filter($arr, fn) keep items that pass a test
array_reduce($arr, fn, start) combine into one value
array_sum() / array_product() total / product

Search

in_array(), array_search(), array_key_exists()

Combine and split

array_merge(), array_combine($keys, $values), array_slice($arr, 0, 5), array_chunk($arr, 3), array_unique(), array_reverse()

Sorting

Function Sorts by Keeps keys?
sort() / rsort() value, asc / desc no
asort() / arsort() value yes
ksort() / krsort() key yes
usort($arr, fn) your own rule no

Sorting functions change the original array and return true.

Spread operator

$all = [...$frontend, ...$backend]; merges arrays (PHP 7.4+).

Example

Example — Working with a product list PHP
<?php
$prices = ['Mouse' => 349, 'Keyboard' => 899, 'Monitor' => 7499, 'Pen Drive' => 499, 'Cable' => 149];

$withGst = array_map(fn($p) => round($p * 1.18), $prices);
$cheap = array_filter($prices, fn($p) => $p < 500);
$total = array_reduce($prices, fn($sum, $p) => $sum + $p, 0);

arsort($prices); // costliest first, keys kept

echo 'Costliest first: ' . implode(', ', array_keys($prices)) . '<br>';
echo 'Under ₹500: ' . implode(', ', array_keys($cheap)) . '<br>';
echo 'Mouse with GST: ₹' . $withGst['Mouse'] . '<br>';
echo 'Total: ₹' . number_format($total) . '<br>';

$frontend = ['HTML', 'CSS', 'JS'];
$backend = ['PHP', 'MySQL', 'PHP'];
$all = array_unique([...$frontend, ...$backend]);
echo 'Skills: ' . implode(', ', $all) . '<br>';
echo 'Pages: ' . json_encode(array_chunk($all, 2));

Output: Costliest first: Monitor, Keyboard, Pen Drive, Mouse, Cable / Under ₹500: Mouse, Pen Drive, Cable / Mouse with GST: ₹412 / Total: ₹9,395 / Skills: HTML, CSS, JS, PHP, MySQL / Pages: grouped in pairs.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which sort keeps the keys of an associative array?

Exercise 2 True / False

array_filter keeps the items for which the callback returns true.

Exercise 3 Fill in the Blank

array() removes duplicate values.

Frequently Asked Questions

sort() changes the array in place and returns true (printed as 1). Sort first, then print the array.