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:

1<?php
2 
3// Some user-generated array of input
4$input = [ ..., ];
5 
6foreach ($input as $field) {
7 if (trim($field) === '' ) {
8 continue;
9 }
10 
11 // Persist the value into the database
12}

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.

1/**
2 * Ensure that the input array has no empty-string values assigned.
3 *
4 * @param array $array
5 *
6 * @return array
7 */
8function array_clean(array $array)
9{
10 // Trim the array input values
11 $array = array_map('trim', $array);
12 
13 // Filter any empty-string values out
14 return array_filter($array, function ($item) {
15 return $item !== '';
16 });
17}

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:

1<?php
2 
3// Some user-generated array of input
4$input = array_clean($request->input('user_input'));
5 
6foreach ($input as $field) {
7 // Persist the value into the database, no longer worrying about saving empty values to the db
8}
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