Get Array Values Recursively with PHP

By  on  

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!

Recent Features

  • By
    Creating Scrolling Parallax Effects with CSS

    Introduction For quite a long time now websites with the so called "parallax" effect have been really popular. In case you have not heard of this effect, it basically includes different layers of images that are moving in different directions or with different speed. This leads to a...

  • By
    How to Create a RetroPie on Raspberry Pi – Graphical Guide

    Today we get to play amazing games on our super powered game consoles, PCs, VR headsets, and even mobile devices.  While I enjoy playing new games these days, I do long for the retro gaming systems I had when I was a kid: the original Nintendo...

Incredible Demos

Discussion

  1. nedt

    No need to create a new array, just use iterators. There is an interface for iterators with values that can be iterators called RecursiveIterator. To wrap a nested array there is RecursiveArrayIterator. And to flatten an RecursiveIterator you can use RecursiveIteratorIterator, which by default only returns the leaves.

    $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
    foreach ($it as $k => $v) {
        var_dump("$k = $v");
    }
    

    If you want to convert it to an array use iterator_to_array():

    $flatten = iterator_to_array($it);
    
    • Jeremy

      Although if you’re going to call iterator_to_array() I think you’ve defeated your stated purpose for using iterators.

    • Rafael

      I just love this blog, I always get to know something new. I didn’t know about this. Very useful!

  2. zdenko
    function flatten_array($arg) {
      return is_array($arg) ? array_reduce($arg, function ($c, $a) { return array_merge($c, flatten_array($a)); },[]) : [$arg];
    }
    

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!