3.1. Array Functions and Callbacks
Array functions allow you to access and manipulate the contents of arrays without having to extract them first. Most, if not all, of the operations you may wish to carry out on "every element of an array" can be carried out using these functions, without requiring the additional infrastructure of a for or foreach loop. Also, many array manipulation tasks require the entire array to be taken into consideration. Sorting is the obvious example here: you can't move the smallest element to the start of the array without looking at all of the array's elements in order to locate the smallest element. Anyone who has tried to write a reasonably efficient sorting algorithm will know that the task is not trivial.
Because there is no way PHP's developers could predict everything you want to do with your array, most of the array functions, as well as the array or arrays in question, take an additional argument known as a callback, which names another function that, depending on what the array function does, would be used to manipulate array elements, or compare them to each other or against some criterion you specify. In this way, PHP needs to provide only implementations of the more abstract aspects of array manipulation, such as mapping and traversing, leaving you free to provide the concrete details of your choice.
Callbacks can be so useful for abstracting functionality, in fact, that a selection of functions are provided to allow their use in almost ...
Get Professional LAMP: Linux®, Apache, MySQL®, and PHP5 Web Development now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.