PHP Functions 7 programs with output 15 Q/A 5 MCQs

Learning Objectives – after this chapter you will be able to:

  • Use the Apache-specific functions available when PHP runs as an Apache module (as in XAMPP).
  • Look up the purpose and syntax of every common array function.
  • Apply array functions for creating, searching, combining, slicing, sorting and walking arrays.
  • Know which array functions were removed in PHP 8.
How to Use the Function Reference Chapters

Part II is a reference to PHP's built-in functions, arranged by category in the same order as the original notes. Each chapter gives a table with the syntax and purpose of each function, marks functions that are no longer available in PHP 8 (with the modern replacement), and then shows example programs with their output.

Parameters in square brackets are optional, e.g. array_keys(array [, search_value]). The complete, always up-to-date reference is the PHP Manual at www.php.net/manual. You can also type a function name after php.net/ – for example php.net/array_map.

Apache Functions

These functions exist only when PHP runs as an Apache module (mod_php), which is how XAMPP runs PHP.

FunctionPurpose
apache_get_modules()Returns an array of the loaded Apache modules.
apache_get_version()Returns the version of Apache that is currently running.
apache_getenv(variable)Returns an Apache sub-process environment variable.
apache_setenv(variable, value [, walk_to_top])Sets an Apache sub-process environment variable.
apache_lookup_uri(filename)Performs a partial request for the URI and returns information about it as an object.
apache_note(note_name [, note_value])Gets or sets values in the Apache notes table.
apache_request_headers()Returns all HTTP request headers as an associative array.
apache_response_headers()Returns all HTTP response headers as an array.
getallheaders()Alias of apache_request_headers().
virtual(filename)Performs an Apache sub-request (like an SSI include virtual).
apache_child_terminate()Stopped the Apache child process after the request – not available in PHP 8 with Apache 2.
ascii2ebcdic(string) / ebcdic2ascii(string)Converted between ASCII and EBCDIC – only on EBCDIC (mainframe) systems; not in normal PHP builds.
File: htdocs/phpbook/ch23/apache.php
<?php
echo "Apache version: " . apache_get_version() . "<br>";
$mods = apache_get_modules();
echo "Loaded modules: " . count($mods) . "<br>";
echo "mod_rewrite loaded? " . (in_array("mod_rewrite", $mods) ? "yes" : "no") . "<br>";
echo "<b>Some request headers sent by the browser:</b><br>";
$h = apache_request_headers();
foreach (["Host", "Accept-Language", "Connection"] as $k) {
    echo "$k: " . ($h[$k] ?? "-") . "<br>";
}
?>
OUTPUT browser · http://localhost/phpbook/ch23/apache.php
Apache version: Apache/2.4.58 (Ubuntu)
Loaded modules: 29
mod_rewrite loaded? yes
Some request headers sent by the browser:
Host: localhost
Accept-Language: -
Connection: keep-alive
Array Functions – Creating and Inspecting
FunctionPurpose
array([...])Creates an array of the given values (short form [...]).
range(low, high [, step])Creates an array of values from low to high.
array_fill(start_index, count, value)Fills an array with a value, a given number of times.
array_fill_keys(keys, value)Fills an array with a value, using the given keys.
array_combine(keys, values)Creates an array using one array for keys and another for values (equal sizes).
compact(var_names...)Creates an array from variables and their values.
extract(array [, flags, prefix])Imports array keys as variables into the current symbol table; flags decide what happens on a conflict, prefix adds a prefix to names.
count(array [, mode])Counts the elements (COUNT_RECURSIVE counts nested elements too). sizeof() is an alias.
array_count_values(array)Counts how many times each value appears; returns value => count.
array_key_exists(key, array)Checks whether a key exists (also for keys whose value is null).
in_array(value, array [, strict])Checks whether a value exists in the array.
array_search(value, array [, strict])Searches for a value and returns its key (or false).
array_keys(array [, search_value])Returns all keys, or the keys holding search_value.
array_values(array)Returns all values, re-indexed from 0.
array_key_first(array) / array_key_last(array)Returns the first / last key (PHP 7.3).
File: htdocs/phpbook/ch23/create.php
<?php
echo "<pre>";
print_r(range(0, 20, 5));
print_r(array_fill(5, 3, "x"));
print_r(array_combine(["a", "b", "c"], [1, 2, 3]));
$city = "Bhopal"; $state = "MP";
print_r(compact("city", "state"));
print_r(array_count_values(["php", "sql", "php", "js", "php"]));
$ages = ["Peter" => 32, "Asha" => 21];
var_dump(array_key_exists("Asha", $ages));
echo "array_search(21) = " . array_search(21, $ages) . "\n";
echo "array_keys: " . implode(", ", array_keys($ages)) . "\n";
echo "array_key_last: " . array_key_last($ages) . "\n";
echo "</pre>";
?>
OUTPUT browser · http://localhost/phpbook/ch23/create.php
Array
(
    [0] => 0
    [1] => 5
    [2] => 10
    [3] => 15
    [4] => 20
)
Array
(
    [5] => x
    [6] => x
    [7] => x
)
Array
(
    [a] => 1
    [b] => 2
    [c] => 3
)
Array
(
    [city] => Bhopal
    [state] => MP
)
Array
(
    [php] => 3
    [sql] => 1
    [js] => 1
)
bool(true)
array_search(21) = Asha
array_keys: Peter, Asha
array_key_last: Asha
Array Functions – Adding, Removing and Combining
FunctionPurpose
array_push(array, values...)Adds values to the end; returns the new number of elements. Opposite of array_pop().
array_pop(array)Removes and returns the last element.
array_unshift(array, values...)Adds values to the beginning; returns the new count. Opposite of array_shift().
array_shift(array)Removes and returns the first element.
array_merge(arrays...)Merges arrays. Later string keys overwrite earlier ones; numeric keys are appended and re-numbered.
array_merge_recursive(arrays...)Like array_merge(), but values with the same string key are merged into arrays.
array_slice(array, offset [, length, preserve_keys])Returns a part of the array.
array_splice(array, offset [, length, replacement])Removes a part of the array and optionally replaces it.
array_pad(array, size, value)Pads the array to the given size with a value.
array_chunk(array, size [, preserve_keys])Splits an array into chunks of the given size.
array_flip(array)Exchanges keys and values.
array_reverse(array [, preserve_keys])Returns the array in reverse order.
array_unique(array)Removes duplicate values.
array_rand(array [, num])Picks one or more random keys.
shuffle(array)Shuffles the array into random order.
File: htdocs/phpbook/ch23/modify.php
<?php
$stack = ["php", "mysql"];
echo "array_push returns " . array_push($stack, "html", "css") . ": " . implode(", ", $stack) . "<br>";
echo "array_pop removed '" . array_pop($stack) . "': " . implode(", ", $stack) . "<br>";
array_unshift($stack, "linux");
echo "after array_unshift: " . implode(", ", $stack) . "<br>";
echo "array_shift removed '" . array_shift($stack) . "'<br>";
echo "array_merge: " . implode(", ", array_merge([1, 2], [3, 4], [5])) . "<br>";
$a = ["x" => 1, "y" => 2];
$b = ["y" => 20, "z" => 30];
echo "array_merge with keys: " . json_encode(array_merge($a, $b)) . "<br>";
echo "array_merge_recursive: " . json_encode(array_merge_recursive($a, $b)) . "<br>";
$n = [10, 20, 30, 40, 50];
echo "array_slice(1, 3): " . implode(", ", array_slice($n, 1, 3)) . "<br>";
array_splice($n, 1, 2, ["A", "B", "C"]);
echo "after array_splice: " . implode(", ", $n) . "<br>";
echo "array_pad: " . implode(", ", array_pad([1, 2], 5, 0)) . "<br>";
echo "array_chunk: " . json_encode(array_chunk([1, 2, 3, 4, 5], 2)) . "<br>";
echo "array_flip: " . json_encode(array_flip(["a" => 1, "b" => 2])) . "<br>";
echo "array_unique: " . implode(", ", array_unique([3, 1, 3, 2, 1])) . "<br>";
echo "array_reverse: " . implode(", ", array_reverse([1, 2, 3]));
?>
OUTPUT browser · http://localhost/phpbook/ch23/modify.php
array_push returns 4: php, mysql, html, css
array_pop removed 'css': php, mysql, html
after array_unshift: linux, php, mysql, html
array_shift removed 'linux'
array_merge: 1, 2, 3, 4, 5
array_merge with keys: {"x":1,"y":20,"z":30}
array_merge_recursive: {"x":1,"y":[2,20],"z":30}
array_slice(1, 3): 20, 30, 40
after array_splice: 10, A, B, C, 40, 50
array_pad: 1, 2, 0, 0, 0
array_chunk: [[1,2],[3,4],[5]]
array_flip: {"1":"a","2":"b"}
array_unique: 3, 1, 2
array_reverse: 3, 2, 1
Array Functions – Comparing (Difference and Intersection)
FunctionPurpose
array_diff(array1, arrays...)Values of array1 that are not present in the other arrays. Opposite of array_intersect().
array_diff_assoc(array1, arrays...)Like array_diff(), but keys are compared too.
array_diff_key(array1, arrays...)Compares only the keys.
array_diff_uassoc / array_udiff / array_udiff_assoc / array_udiff_uassocDifference using user-defined callback functions for values and/or keys.
array_intersect(array1, arrays...)Values of array1 that are present in all other arrays. Opposite of array_diff().
array_intersect_assoc(array1, arrays...)Like array_intersect(), but keys are compared too.
array_intersect_key / array_intersect_uassoc / array_uintersect / array_uintersect_assoc / array_uintersect_uassocIntersection by keys and/or with user-defined callback functions.
File: htdocs/phpbook/ch23/compare.php
<?php
$batchA = ["Asha", "Ravi", "Neha", "John"];
$batchB = ["Ravi", "John", "Kiran"];
echo "Only in A (array_diff): " . implode(", ", array_diff($batchA, $batchB)) . "<br>";
echo "In both (array_intersect): " . implode(", ", array_intersect($batchA, $batchB)) . "<br>";
$x = ["a" => "green", "b" => "brown", "c" => "blue", "red"];
$y = ["a" => "green", "yellow", "red"];
echo "array_diff_assoc: " . json_encode(array_diff_assoc($x, $y)) . "<br>";
echo "array_intersect_assoc: " . json_encode(array_intersect_assoc($x, $y)) . "<br>";
echo "array_udiff (case-insensitive): " .
     implode(", ", array_udiff(["PHP", "Java"], ["php"], 'strcasecmp'));
?>
OUTPUT browser · http://localhost/phpbook/ch23/compare.php
Only in A (array_diff): Asha, Neha
In both (array_intersect): Ravi, John
array_diff_assoc: {"b":"brown","c":"blue","0":"red"}
array_intersect_assoc: {"a":"green"}
array_udiff (case-insensitive): Java
Array Functions – Callbacks and Calculation
FunctionPurpose
array_map(callback, array, ...)Applies a function to every element and returns the new array.
array_filter(array [, callback, mode])Returns only the elements for which the callback returns true (without callback: removes falsy values).
array_reduce(array, callback [, initial])Reduces the array to a single value using a callback.
array_walk(array, callback [, arg])Applies a function to every element (by reference possible); returns true.
array_walk_recursive(array, callback [, arg])Like array_walk(), also inside nested arrays.
array_sum(array)Calculates the sum of the values.
array_product(array)Calculates the product of the values.
array_column(array, column_key [, index_key])Returns the values of one column of a two-dimensional array.
File: htdocs/phpbook/ch23/callbacks.php
<?php
$prices = [120, 450, 80, 999];
echo "array_map (+18% GST): " . implode(", ", array_map(fn($p) => $p * 1.18, $prices)) . "<br>";
echo "array_filter (> 100): " . implode(", ", array_filter($prices, fn($p) => $p > 100)) . "<br>";
echo "array_reduce (total): " . array_reduce($prices, fn($c, $p) => $c + $p, 0) . "<br>";
echo "array_sum: " . array_sum($prices) . ", array_product([2,3,4]): " . array_product([2, 3, 4]) . "<br>";
$marks = ["Asha" => 82, "Ravi" => 64];
array_walk($marks, function (&$m, $name) { $m = "$name scored $m"; });
echo "array_walk: " . implode("; ", $marks) . "<br>";
$students = [
    ["id" => 1, "name" => "Asha"],
    ["id" => 2, "name" => "Ravi"],
];
echo "array_column: " . json_encode(array_column($students, "name", "id"));
?>
OUTPUT browser · http://localhost/phpbook/ch23/callbacks.php
array_map (+18% GST): 141.6, 531, 94.4, 1178.82
array_filter (> 100): 120, 450, 999
array_reduce (total): 1649
array_sum: 1649, array_product([2,3,4]): 24
array_walk: Asha scored 82; Ravi scored 64
array_column: {"1":"Asha","2":"Ravi"}
Array Functions – Sorting
FunctionPurpose
sort(array)Sorts values in ascending order (keys are re-numbered). Opposite of rsort().
rsort(array)Sorts values in descending order.
asort(array)Sorts by value in ascending order, keeping the key/value relationship.
arsort(array)Sorts by value in descending order, keeping the key/value relationship.
ksort(array)Sorts by key in ascending order, keeping the key/value relationship.
krsort(array)Sorts by key in descending order, keeping the key/value relationship.
usort / uasort / uksort (array, callback)Sorts with a user-defined comparison function (by value, by value keeping keys, by key).
natsort(array)"Natural order" sort of alphanumeric strings (case-sensitive): img2 before img10.
natcasesort(array)Natural order sort, case-insensitive.
array_multisort(array1 [, order, flags, ...])Sorts several arrays at once, or a multidimensional array by columns.
File: htdocs/phpbook/ch23/sorting.php
<?php
$files = ["img12.png", "img10.png", "IMG2.png", "img1.png"];
$a = $files; sort($a);
echo "sort: " . implode(", ", $a) . "<br>";
$b = $files; natsort($b);
echo "natsort: " . implode(", ", $b) . "<br>";
$c = $files; natcasesort($c);
echo "natcasesort: " . implode(", ", $c) . "<br>";
$stock = ["pen" => 40, "book" => 15, "bag" => 25];
arsort($stock);
echo "arsort: " . json_encode($stock) . "<br>";
krsort($stock);
echo "krsort: " . json_encode($stock) . "<br>";
$names = ["Ravi", "Asha", "Neha"];
$marks = [64, 82, 82];
array_multisort($marks, SORT_DESC, $names, SORT_ASC);
echo "array_multisort: " . implode(", ", array_map(fn($n, $m) => "$n($m)", $names, $marks));
?>
OUTPUT browser · http://localhost/phpbook/ch23/sorting.php
sort: IMG2.png, img1.png, img10.png, img12.png
natsort: IMG2.png, img1.png, img10.png, img12.png
natcasesort: img1.png, IMG2.png, img10.png, img12.png
arsort: {"pen":40,"bag":25,"book":15}
krsort: {"pen":40,"book":15,"bag":25}
array_multisort: Asha(82), Neha(82), Ravi(64)
Array Functions – The Internal Pointer

Every array has an internal pointer to its "current" element.

FunctionPurpose
current(array)Returns the value of the current element. pos() is an alias.
key(array)Returns the key of the current element.
next(array)Moves the pointer to the next element and returns its value (false at the end). Opposite of prev().
prev(array)Moves the pointer to the previous element and returns its value.
reset(array)Moves the pointer to the first element and returns its value.
end(array)Moves the pointer to the last element and returns its value.
each(array)Returned the current key/value pair and advanced the pointer – removed in PHP 8.0; use foreach.
File: htdocs/phpbook/ch23/pointer.php
<?php
$days = ["Mon", "Tue", "Wed", "Thu"];
echo "current: " . current($days) . "<br>";
echo "next: " . next($days) . "<br>";
echo "next: " . next($days) . ", key: " . key($days) . "<br>";
echo "prev: " . prev($days) . "<br>";
echo "end: " . end($days) . "<br>";
echo "reset: " . reset($days);
?>
OUTPUT browser · http://localhost/phpbook/ch23/pointer.php
current: Mon
next: Tue
next: Wed, key: 2
prev: Tue
end: Thu
reset: Mon
Key Takeaways
  • Apache functions such as apache_get_version() and apache_request_headers() work when PHP runs as an Apache module, as in XAMPP.
  • Creating/inspecting: range, array_fill, array_combine, compact, extract, count, in_array, array_search, array_keys, array_values.
  • Modifying: array_push/pop, array_unshift/shift, array_merge, array_slice/splice, array_unique, array_reverse.
  • Comparing: array_diff* and array_intersect* (the u versions use callbacks).
  • Callbacks: array_map, array_filter, array_reduce, array_walk; calculating: array_sum, array_product, array_column.
  • Sorting: sort/rsort, asort/arsort, ksort/krsort, usort, natsort, array_multisort.
  • each() was removed in PHP 8 – use foreach.
Program File

Extract the ZIP into C:\xampp\htdocs. It creates the folder phpbook/ch23 used in the file labels above; open the programs at http://localhost/phpbook/… with Apache (and MySQL, where needed) started in the XAMPP Control Panel.

Question / Answer (15 questions)

Answer : Only when PHP runs as an Apache module (mod_php), as in XAMPP. They are not available with the CLI, FastCGI/PHP-FPM or the built-in server.

Answer : An associative array of all HTTP request headers sent by the browser, such as Host, User-Agent and Accept-Language. getallheaders() is an alias.

Answer : array_combine() builds one array using the first array as keys and the second as values; array_merge() joins several arrays into one.

Answer : compact("city", "state") creates an array from variables, using their names as keys; extract() does the reverse – it creates variables from array keys.

Answer : An associative array where each distinct value of the input is a key and the number of its occurrences is the value.

Answer : array_push() adds elements to the end of an array; array_unshift() adds them to the beginning. Both return the new number of elements.

Answer : array_pop() removes and returns the last element; array_shift() removes and returns the first element (re-indexing numeric keys).

Answer : For string keys, the value from the later array overwrites the earlier one; numeric keys are appended and re-numbered.

Answer : array_slice() returns a portion of an array without changing it; array_splice() removes a portion from the original array and can insert replacement elements.

Answer : array_diff() returns values of the first array not present in the others; array_intersect() returns values of the first array present in all the others.

Answer : Keys are compared as well as values, so an element is different if either its key or its value differs.

Answer : array_map() transforms every element with a callback; array_filter() keeps only elements for which the callback returns true; array_reduce() combines all elements into one value.

Answer : Sorting alphanumeric strings the way a human would, so "img2" comes before "img10". natsort() is case-sensitive, natcasesort() case-insensitive.

Answer : next(), prev(), reset() and end(); current() (pos()) and key() read the element at the pointer.

Answer : each(), which returned the current key/value pair and advanced the pointer. Use a foreach loop instead.
MCQ Test : Check Your Understanding (5 questions)

Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.

Q1. Which function adds elements to the beginning of an array?

Show Answer

Correct Answer : B. array_unshift()
array_unshift() prepends values.

Q2. array_diff([1,2,3], [2,3,4]) returns:

Show Answer

Correct Answer : A. [1]
Only 1 is not present in the second array.

Q3. Which function keeps key/value pairs while sorting by value in descending order?

Show Answer

Correct Answer : C. arsort()
arsort() sorts by value descending and preserves keys.

Q4. Which function returns one column of a two-dimensional array?

Show Answer

Correct Answer : A. array_column()
array_column($rows, "name") extracts that column.

Q5. Which array function no longer exists in PHP 8?

Show Answer

Correct Answer : B. each()
each() was removed in PHP 8.0.

Bibliography/References

The notes on this page are the author’s own compilation from the e-book PHP: Basics to Advance. Every program was run on Apache with PHP 8 and MariaDB, and the output shown is the real result of that run. The works listed below were consulted and are cited for attribution and further reading. Product names and trademarks belong to their respective owners.

  1. The PHP Group. (n.d.). PHP Manual – Array Functions. https://www.php.net/manual/en/ref.array.php
  2. The PHP Group. (n.d.). PHP Manual – Apache Functions. https://www.php.net/manual/en/ref.apache.php
  3. The PHP Group. (n.d.). PHP Manual – Sorting Arrays. https://www.php.net/manual/en/array.sorting.php
  4. The PHP Group. (n.d.). PHP Manual – Backward incompatible changes (PHP 8.0). https://www.php.net/manual/en/migration80.incompatible.php