Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

dynamic n-dimensional arrays

dynamically getting array value from unknown key depth



8:02 am on Jun 12, 2009 (gmt 0)

5+ Year Member

I have a place in my code where it has to check back on a previous array value from a duplicate array. There's a bit of recursion, and through each cycle, I store the array key at that level.
So if this is my array:
$example['test'][1]['stuff'] = 'hi';
at each level I store the keys like so:
$key_list = "test¦1¦stuff";

The array depth is unknown, can be a n-dimensional array, but once it gets to the value, it needs to compare it to the original array it was duplicated from. It follows the same key path, eg:
But I can't go
$keys = explode($key_list);
Because it might only need $keys[0] or could go to $keys[n]

How do I go about that?
I tried stuff like:
$key_list = "[test][1][stuff]";
But as expected, that failed ( I was really hoping )

Any ideas?



8:22 am on Jun 12, 2009 (gmt 0)

5+ Year Member

I suppose I could go:

$key_list = "[test][1][stuff]";
eval("\$equivalent &= \$original_array.$key_list");

But there's got to be a better way than that, without eval...


11:43 am on Jun 12, 2009 (gmt 0)

5+ Year Member

So I wrote this function:

function &get_array_by_key_array(&$array, $key_array = array()) {
$temp_array =& $array;
foreach ($key_array as $key => $value) {
if (isset($temp_array[$value])) {
$temp_array =& $temp_array[$value];
} else {
return null;
return $temp_array;

which works great.

But is there any language construct that will let me do it without any extra function, or just a better way?


4:19 pm on Jun 12, 2009 (gmt 0)

5+ Year Member

Just out of interest, how come you are using multidimensional arrays in the first place?

If you could explain the problem/task that you are trying to complete, perhaps we could recommend a data structure or more streamlined idea.


7:59 pm on Jun 12, 2009 (gmt 0)

5+ Year Member

I'm extending the CodeIgniter Form_Validation library. I don't want to completely rework it. It only had partial support for array input names. <input name="item[]"> I needed support for a large changeable number of input fields. Entering serial numbers for (lots * quantity per lot) for inventory purposes. I use CodeIgniter a lot so I wanted a versatile dynamic solution. I am basically stuck withing the confines of how it already works. I wanted to be able to go <input name="item[x][y][z]">

Featured Threads

Hot Threads This Week

Hot Threads This Month