Blog

[PHP] Array Max Filter by Key

Posted on

PHP's array_filter function is great way of manipulating arrays. Since PHP version 5.3, the callback function argument can include closures – references to external variables, increasing the utility of array_filter. Today, I came across a situation where I wanted to manipulate an associative array by filtering its elements using a regular expression match on the index so I wrote the following function that will hopefully benefit others looking for this solution.

    /** 
    * Finds and optionally filters the index of the highest value in an array.
    * 
    * @author  Akin Williams <aowilliams@arstropica.com>
    * 
    * @param   array $array Array to be filtered
    * @param   string $pattern Optional, regular expression pattern for index filter.
    * @return  bool|string|int index of element with highest value matching pattern or false if no match
    **/
    function array_max_index_filter($array, $pattern=null) {
        $output = false;
        if (is_array($array) && (empty($array) === false)) {
            $filtered_keys = array_filter(array_keys($array), function ($el) use (&$pattern) { return ($pattern) ? preg_match($pattern, $el) : true; });
            $filtered_array = array_intersect_key($array, array_flip($filtered_keys));
            if (empty($filtered_array) === false) {
                $output = current(array_keys($filtered_array, max($filtered_array)));
            }
        }
        return $output;
    }