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
    CSS Gradients

    With CSS border-radius, I showed you how CSS can bridge the gap between design and development by adding rounded corners to elements.  CSS gradients are another step in that direction.  Now that CSS gradients are supported in Internet Explorer 8+, Firefox, Safari, and Chrome...

  • By
    Vibration API

    Many of the new APIs provided to us by browser vendors are more targeted toward the mobile user than the desktop user.  One of those simple APIs the Vibration API.  The Vibration API allows developers to direct the device, using JavaScript, to vibrate in...

Incredible Demos

  • By
    Create Twitter-Style Dropdowns Using MooTools

    Twitter does some great stuff with JavaScript. What I really appreciate about what they do is that there aren't any epic JS functionalities -- they're all simple touches. One of those simple touches is the "Login" dropdown on their homepage. I've taken...

  • By
    Create a Dojo Lightbox with dojox.image.Lightbox

    One of the reasons I love the Dojo Toolkit is that it seems to have everything.  No scouring for a plugin from this site and then another plugin from that site to build my application.  Buried within the expansive dojox namespace of Dojo is

Discussion

    • 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!

  1. 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!