scott212 Posted March 5, 2007 Share Posted March 5, 2007 Any of you geniuses have any tricks to count the number of dimensions within an array? I'm using the following to check to see if it is multidimensional or not, but I'd like to convert it to return the number of dimensions. Here's what I have: function array_dimen($input) { // see if the array is multidimensional $num_root = count($input); $num_branch = count($input, COUNT_RECURSIVE); if ($num_root < $num_branch) { return 1; } else { return 0; } } Quote Link to comment Share on other sites More sharing options...
pocobueno1388 Posted March 5, 2007 Share Posted March 5, 2007 "Counting elements: Count() and sizeof() count the number of elements in an array. Array_count_values() counts unique values in the array ("set cardinality") and returns an associative array with a frequency table. The unique values from the array will be the keys (indices) for the new array." I got that from this site: <a href="http://www.uri.edu/artsci/com/Logan/teaching/html/com372_spring_2007/html_notes/n3.htm">Here</a> Not sure if counting the elements is the same as counting the dimensions....you can give it a try though. Quote Link to comment Share on other sites More sharing options...
galz Posted June 25, 2009 Share Posted June 25, 2009 I'm aware it's been 2 years since this was posted but as I didn't find any solutions for this matter elsewhere I'm happy to upload mine function array_dimen_count($ArrayInput, $dimCount = 0) { // Count an array dimensions if(is_array($ArrayInput)) { return array_dimen_count(current($ArrayInput), $dimCount + 1); } else { return $dimCount; } } which can be tested with $array = array("color" => array("blue", "red", "green"), "size" => array("small", "medium", "large")); echo 'array size = '. array_dimen_count($array). '<br>'; $array = array("blue", "red", "green", "blue", "blue"); echo 'array size = '. array_dimen_count($array). '<br>'; Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.