How to filter user submitted data easily in PHP?

Written by Chris on August 18, 2008 – 7:29 am -

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

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!



Sphere: Related Content

Related posts on coderchris.com:

  1. Refactor My Code – I Wish I’d Thought of It!
    refactormycode
  2. More Laptop Battery Life Stuff
    I have a Toshi
  3. MySQL 5.1 partitioning and loosing all your databases (or not)!
    I can across a
  4. Bloody MySQL Bugs
    I’m looking
  5. MySQL 5.1 multiple tmpdirs and incorrect key file for table errors
    Well I found o


Tags: , , , , , ,
Posted in PHP, Web Development | Trackback | 1 Comment »

One Comment to “How to filter user submitted data easily in PHP?”

  1. Jasper Says:

    I personally don’t use array map because it’s all well and good when you’re expecting only strings to come through for filtering, but if you’re expecting integers to make up dates and the like, using array map in my experience has always resulted in going back and fixing stuff, or having to do more filtering anyway so it’s a bit of a waste of time.

    Maybe I just haven’t thought about it enough.

Leave a Comment

RSS