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!
![5 Ways that CSS and JavaScript Interact That You May Not Know About]()
CSS and JavaScript: the lines seemingly get blurred by each browser release. They have always done a very different job but in the end they are both front-end technologies so they need do need to work closely. We have our .js files and our .css, but...
![7 Essential JavaScript Functions]()
I remember the early days of JavaScript where you needed a simple function for just about everything because the browser vendors implemented features differently, and not just edge features, basic features, like addEventListener
and attachEvent
. Times have changed but there are still a few functions each developer should...
![Create Digg URLs Using PHP]()
Digg recently came out with a sweet new feature that allows users to create Tiny Digg URLs which show a Digg banner at the top allowing easy access to vote for the article from the page. While I love visiting Digg every once in a...
![CSS Background Animations]()
Background animations are an awesome touch when used correctly. In the past, I used MooTools to animate a background position. Luckily these days CSS animations are widely supported enough to rely on them to take over JavaScript-based animation tasks. The following simple CSS snippet animates...
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.
If you want to convert it to an array use iterator_to_array():
Although if you’re going to call
iterator_to_array()
I think you’ve defeated your stated purpose for using iterators.I just love this blog, I always get to know something new. I didn’t know about this. Very useful!