How to filter user submitted data easily in PHP?

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 icon smile How to filter user submitted data easily in PHP?

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);

Easy huh?

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!





Related posts on coderchris.com:

  1. Handling CType Data With SimpleXML in PHP
    If you're new to SimpleXML then the output and representation of complex XML data...
  2. User Agent
    Of all the websites out there that I visit on a daily basis, I...
  3. Refactor My Code – I Wish I’d Thought of It!
    refactormycode.com is a fledgling website setup as a project by French Canadian  Ruby Developer...
  4. ctype_digit rtfm!
    For the last 5-10 minutes I've been wondering why a check on a variable...
  5. Advanced Syntax-Hilighting Online Code Editors – A WordPress IDE?
    When I write plugins for wordpress I like to do it on a test...