Posts tagged array_map
Posted using ShareThis
Firstly, as you can see this is my first post made as a direct result of using the ShareThis bookmarklet, which is pretty neat as it actually worked
Secondly and more importantly, I wanted to flag this up on my blog as it's something that quite often gets missed in PHP which is actually a very powerful tool.
As the author of the post above mentions, array_map() can be a useful function when sanitizing user data, but it has so many more uses too when dealing with the transformation of a data-set.
Basically a call such as $new_data = array_map('process_data', $old_data); will allow you to transform each element in the $old_data array to a new element in the $new_data array via the function called process_data.
What's more you can manipulate multiple data-sets in this way too by specifying multiple arrays, so long as process_data() can take in the arguments.
For example lets say we have process_data($item1, $item2, $item3) which manipulates $item1, $item2, $item3 to produce a single result.
If we need to perform this calculation on a bulk set of data we can do
$new_data = array_map('process_data', $array_of_item1, $array_of_item2, $array_of_item3);
I still see people performing these transformations, calculations, whatever, using for, foreach and while loops which can be prone to failure under certain conditions, and are probably less efficient code than simply making this call.
So why don't more people use it?Â I don't know, but maybe this post will help raise awareness!