Jump to content

count array dimensions


scott212

Recommended Posts

Any of you geniuses ;D 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;
	}
}

Link to comment
Share on other sites

"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.

Link to comment
Share on other sites

  • 2 years later...

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>';

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.