Callback Functions in PHP

Consider the following script:

$input_file = file('generic.txt');
foreach($input_file as $k=>$line)
{
$input_file[$k] = rtrim($line);
}

You’re loading in a text file as an array of single lines. PHP doesn’t throw away the linebreak characters at the end, so now that they have served their purpose, you want to drop them yourself. Writing an entire loop and using two extra variables within it seems long-winded. For a start, you have to keep in mind that $line is copied, so $line=rtrim($line); won’t work, meaning that you have to refer back to the original by array and key. Either that, or remember to declare $line by reference by writing foreach($input_file as &$line). Mistakes in either will mean that the final array won’t have its lines trimmed.

Now consider this:

$input_file = array_map('rtrim', file('generic.txt'));

This line of code achieves the same effect. file() returns an array containing the lines of generic.txt; array_map() applies the function rtrim() to each element of that array, and returns the resulting “trimmed” array.

There are several functions that abstract the most common reasons for iterating over an array, reducing the need for writing loops and other flow-control statements. While writing one-liners solely for the sake of it can lead to hard-to-read code, cutting down the number of “moving parts” in a program can help reduce the incidence of error.

When you have an array in which you have a task to perform on each element in turn, array_map() and array_walk() deserve consideration. There are other functions that employ so-called callback functions in a similar fashion to save you having to call a function on every element of an array yourself.

Social Network Widget by Acurax Small Business Website Designers
Visit Us On FacebookVisit Us On Twitter