Go Premium for a chance to win a PS4. Enter to Win

x
Solved

# Determining how 'deep' an element of a multidimensional array is

Posted on 2009-04-02
Medium Priority
202 Views
I need to determine how 'deep' an element is within a multidimensional array. For example, following the code snippet, how can I determine whether an element is in the first level, the second level, the third level, etc.? How can I determine that "Vancouver" is nested three levels deep?

Ideally I would be looking for a return of an integer - so looking for "Countries" would return 0, "USA" would return 1, "Seattle" would return 2, etc.
``````\$myArray = array(
"Countries" => array(
"Vancouver", "Toronto"),
"USA" => array(
"New York", "Seattle"),
),
);
``````
0

LVL 39

Accepted Solution

Roger Baklund earned 2000 total points
ID: 24055662
Try this:
``````function howDeep(\$a,\$target,\$level=0) {
if(in_array(\$target,array_keys(\$a)))
return \$level;
foreach(\$a as \$key=>\$sub_array) {
if(is_array(\$sub_array)) {
\$tmp = howDeep(\$sub_array,\$target,\$level+1);
if(\$tmp)
return \$tmp;
} elseif(\$sub_array==\$target)
return \$level;
}
return false;
}
echo howDeep(\$myArray,'Seattle');
``````
0

LVL 1

Author Comment

ID: 24056056
Perfect - thanks!
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this. Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it i…
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
###### Suggested Courses
Course of the Month8 days, 8 hours left to enroll