Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

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

Posted on 2009-04-02
2
197 Views
Last Modified: 2012-05-06
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(
				"Canada" => array(
						"Vancouver", "Toronto"),
				"USA" => array(
						"New York", "Seattle"),
				     ),
		);

Open in new window

0
Comment
Question by:radarhill
2 Comments
 
LVL 39

Accepted Solution

by:
Roger Baklund earned 500 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');

Open in new window

0
 
LVL 1

Author Comment

by:radarhill
ID: 24056056
Perfect - thanks!
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

This article discusses how to create an extensible mechanism for linked drop downs.
3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
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…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

828 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question