Deric Cain

Tech ramblings of a true #geek.


Arrays are everywhere! - Part 1

March 18th, 2016


One of the most used data types in development is arrays. They are used so much, in fact, that PHP has a ton of different built-in array functions. I am going to do a series of the different array functions that PHP offers. Let’s look at a couple and how they can be useful.

array_unique()

If you have an array that may contain duplicate values, array_unique() could come in handy to help you get only the values that are unique. Think of it like MySQL’s DISTINCT clause For example…

$colors = [
  'red',
  'green',
  'yellow',
  'green',
  'blue',
  'red'
];

$unique_colors = array_unique($colors);

// Output...
$unique_colors = [
  'red',
  'green',
  'yellow',
  'blue'
]:

It’s an easy way to get an array without the duplicate values.

array_map()

If you need to apply a function to all of the values in an array, array_map() is a great function for that. Let’s say we have a form with quite a few fields which we want to collect and pass to a DB. Of course, this form will need to be sanitized. array_map() can help us with that. We will create a method called sanitize()

Disclaimer: I am in no way saying this is all you need to do to secure user inputted data. This is just an example of a helper

/**
 * Sanitizes the $_POST array.
 *
 * @param $post_data
 * @return array
 */
public static function sanitize($post_data)
{
  // Take the parameter and use a callback function to clean the data.
  // $post_field represents each input field in the form
  $post_array = array_map(function ($post_field) {
    // Run strip_tags and trim the data from the field
    return strip_tags(trim($post_field));
  }, $post_data);

  // Send the sanitized array back
  return $post_array;
}

Now, we have a static method that can be called when we need to sanitize some user inputted data. We can call it like Validate::sanitize($_POST) assuming that the sanitize() method lives in the Validate class. Of course, you are not limited to just applying sanitize methods to each class, you can apply any function needed to each value in the array.

I will look at some more array functions in another post. If you have any suggestions or comments, follow me on Twitter and give me shout!


blog comments powered by Disqus