Michael Dyrynda
Home Blog Podcasts
 
Cleaning array values with ease October 26th, 2015

On more than one occasion, I've found myself executing some PHP along the lines of this:

<?php

// Some user-generated array of input
$input = [ ..., ];

foreach ($input as $field) {
    if (trim($field) === '' ) {
        continue;
    }

    // Persist the value into the database
}

This has happened one time too many now, and seeing as pretty much all of my projects now are built on top of composer, adding a helpers.php file into my project and autoloading it makes including a generic function to handle this really easy.

/**
 * Ensure that the input array has no empty-string values assigned.
 *
 * @param  array  $array
 *
 * @return array
 */
function array_clean(array $array)
{
    // Trim the array input values
    $array = array_map('trim', $array);

    // Filter any empty-string values out
    return array_filter($array, function ($item) {
        return $item !== '';
    });
}

Now, any time you need to work with a one-dimensional array that may have empty fields in it that you don't want to use, you can tidy up the earlier example a little bit:

<?php

// Some user-generated array of input
$input = array_clean($request->input('user_input'));

foreach ($input as $field) {
    // Persist the value into the database, no longer worrying about saving empty values to the db
}
I'm a real developer ™
Michael Dyrynda

@michaeldyrynda

I am a software developer specialising in PHP and the Laravel Framework, and a freelancer, blogger, and podcaster by night.

Proudly hosted with Vultr

Syntax highlighting by Torchlight