Tuesday 14 August 2018

Get Array Values Recursively with PHP

I've been helping to write a WordPress plugin (I'm not ready to share it yet) and one of the tasks required is validating an array of user-selected values against a list of known valid values. The known valid array is actually a key=>value array so unfortunately array_values wont help get the simple list I'd like.


Instead a more advanced custom function was needed:
// http://php.net/manual/en/function.array-values.php 

function array_values_recursive($array) { 
 $flat = array(); 
           foreach($array as $value) { 
              if (is_array($value)) {
                    $flat = array_merge($flat, array_values_recursive($value)); 
             } else { 
                   $flat[] = $value; 
            } 
        } 
  return $flat; 
}


This recursive function dives into arrays, even key=>value arrays, to retrieve the final list of values. Thank you PHP.net!

0 comments:

Post a Comment