I want to call a function on each element in an array. This is obviously very easy with a foreach()
, but where I start breaking down is when arrays contain arrays. Can someone help me out with a function that will execute some code for every key -> value pair from a set of arrays within arrays. The depth could, in theory, be infinite, but a good limit would be 3 iterations (array in array in array) if recursion couldn't work.
An example array would be one taken from $_POST below:
Array ( [languages] => Array ( [0] => php [1] => mysql [2] => inglip ) [rates] => Array ( [incall] => Array ( [1hr] => 10 ) [outcall] => Array ( [1hr] => 10 ) ) )
Just to make sure, what I want to do is run a piece of code (a function) that is passed every 'end node' in the array structure, so in the example above, it would be called when...
[0] => php [1] => mysql [2] => inglip [1hr] => 10 [1hr] => 10
... is found.
Thanks for any help,
James
Typically, in this kind of situation, you'll have to write a recursive function -- which will deal with an item if it's not an array ; and call itself on an item if it's an array.
Here, you could have something like this :
And calling this recursive function on your array :
Would get you :
If you want to run a function on every element of a deep array, you can use array_walk_recursive()
If you want to iterate over each element with
foreach
, you need a recursive iterator as mentionned previously.If you're not sure which one to use, go with
foreach
+ recursive iterator. It's easier to grasp for most people.