Here is a tour of array functions you will reach for often.
array_merge(): join arrays
<?php
$a = ["php", "sql"];
$b = ["css", "js"];
echo implode(", ", array_merge($a, $b));
php, sql, css, js
array_slice(): take a part
<?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
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
<?php
$tags = ["php", "web", "php", "css", "web"];
echo implode(", ", array_unique($tags));
php, web, css
array_chunk(): split into groups
Perfect for grids and pages.
<?php
$items = [1, 2, 3, 4, 5, 6, 7];
foreach (array_chunk($items, 3) as $row) {
echo implode(" ", $row) . "\n";
}
1 2 3
4 5 6
7
array_diff() and array_intersect()
<?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
a, c
b, d
range(): make a sequence
<?php
echo implode(" ", range(1, 5)) . "\n";
echo implode(" ", range(0, 20, 5)) . "\n";
echo implode(" ", range("a", "e"));
1 2 3 4 5
0 5 10 15 20
a b c d e
array_reverse() and array_sum()
<?php
$numbers = [1, 2, 3];
echo implode(", ", array_reverse($numbers)) . "\n";
echo array_sum($numbers) . "\n";
echo array_product($numbers);
3, 2, 1
6
6
compact() and extract()
compact() builds an array from variables, using their names as keys.
<?php
$name = "Isha";
$city = "Kochi";
print_r(compact("name", "city"));
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.
| Need | Function |
|---|---|
| Is a value in the list | in_array() |
| Position of a value | array_search() |
| Add / remove ends | array_push(), array_pop(), array_shift(), array_unshift() |
| Transform | array_map() |
| Filter | array_filter() |
| Combine to one value | array_reduce() |
| Sort | sort(), usort(), ksort() |