A Custom PHP Function for Recursive Array Filtering

In PHP, working with multidimensional arrays often requires recursive functions to handle nested data structures.

In this blog post, we'll explore an enhanced version of a recursive function designed to filter and trim data within a multidimensional array.

I came up with this function while I was working on a Mastercard Payment Gateway Services (MPGS) integration for a client's project.

Here, I needed this function to avoid empty array elements and trim the array elements.

Initially, I developed a basic version that handled recursive filtering. Later, it came to my mind that I needed to handle both recursive filtering and trimming whitespace from strings, so I extended it.

Prerequisite

You need to have a basic understanding of PHP to follow this article. This guide is aimed at mid-level PHP developers.

The Function

The original function handled arrays recursively, removing empty elements effectively. Here’s the initial version of the function:

public function filterDataRecursively($array = [])
{
    foreach ($array as &$value) {
        if (is_array($value)) {
            $value = $this->filterDataRecursively($value);
        }
    }

    return array_filter($array);
}


Limitations of the Initial Version:

This function only processes arrays and does not handle other types of elements within the array, such as strings.

To address this limitation, I extended the function to trim whitespace from string elements while maintaining the recursive filtering of arrays. Here’s the enhanced version:

public function filterDataRecursively($array = [])
{
    $callback = function ($item) {
        if (is_array($item)) {
            return $this->filterDataRecursively($item);
        } elseif (is_string($item)) {
            return trim($item);
        }

        return $item;
    };

    $array = array_map($callback, $array);

    return array_filter($array);
}


How It Works:

  1. Callback Function: A callback function is defined to process each element in the array. If an element is an array, the function calls itself recursively. If an element is a string, it trims any leading and trailing whitespace.
  2. array_map: This function applies the callback to each element in the array, ensuring every item is processed accordingly.
  3. array_filter: Finally, array_filter removes any empty elements from the processed array.

After applying the callback to all elements using array_map, the function filters out any false-y values (like null, false, empty strings, etc.) using array_filter.

This enhanced version not only preserves the original functionality but also extends it by ensuring strings are clean and free of unnecessary whitespace, making your data cleaner and more reliable.

Tip

I would like to share a bonus tip with this article. While the PHP method we've discussed above is primarily designed for use within PHP classes, there's a neat trick to make it even handier: crafting it as a PHP helper function.

Here's how you can do it:

if (!function_exists('filter_trim_recursive_array')) {
    function filter_trim_recursive_array($array = [])
    {
        $callback = function ($item) {
            if (is_array($item)) {
                return filter_trim_recursive_array($item);
            } elseif (is_string($item)) {
                return trim($item);
            }
            return $item;
        };

        $array = array_map($callback, $array);
        return array_filter($array);
    }
}

 

Package

Additionally, I'd like to mention that I've created an MPGS package on top of the Omnipay payment gateway integration library. You can find the package on my GitHub profile.

If you have any feedback or feature submissions for the library, feel free to submit a pull request following the coding standards outlined in the Omnipay library's guidelines.

Your contributions are highly appreciated!

Conclusion

By extending the original recursive array filtering function to include trimming of string elements, we’ve created a more robust and versatile tool.

This small but significant enhancement can save you time and effort in managing arrays and ensuring your data is as clean as possible.

Thank you for taking the time to read this post. I hope you find this enhanced PHP function useful in your projects. If you have any questions or suggestions, feel free to leave a comment here.

Happy coding!