As a developer is sometimes necessary to manipulate all (or respectively most) of the entries of a given array. Within this post I’ll explain the almight array_map function in detail.
Just image you’re deal with the following array:
$pioneers = array('alan turing', 'charles babbage', 'george boole');
Now, your boss tells you that you have to formate all names in a cute way such as Alan Turing instead of alan turing. Of course you can use the powerful foreach function in the following way:
$data = array();
foreach ( $pioneers as $pioneer ) {
$data[] = ucwords($pioneer);
}
Well, that’s not that bad. But if the project will grow the source code has to be updated later on. And according to advanced developers a programm is getting more complex the more lines of code it contains. Therefore it’s important to reduce the lines of code in such a was that the source code is small on one hand but also easy to read and understand on the other hand. That’s when the almighty array_map function comes into game. With array_map the functionality shown above can be written in only one one line. Thereby the function array_map needs two parameters. The first parameter is the callback e.g. the function to call. The second parameter is the array to manipulate. The example below shows how to use the array_map function:
$data = array_map('ucwords', $pioneers);
Now, printing the $data array will deliver the following result in both cases:
array(3) {
[0]=>
string(11) "Alan Turing"
[1]=>
string(15) "Charles Babbage"
[2]=>
string(12) "George Boole"
}
no comment untill now