9

I am trying to use a function whereby I see how tall (y axis) a two dimensional array is in PHP. How would you suggest that I do this? Sorry, I am new to PHP.

1
  • @phihag gives a very elegant solution... there are no truly 2-dimensional arrays in PHP, the 'array of the array' can be any length, so you would have to get the largest 'array of array'. Commented Mar 8, 2011 at 20:11

7 Answers 7

26
max(array_map('count', $array2d))
Sign up to request clarification or add additional context in comments.

Comments

4

If the y-axis is the outer array, then really just count($array). The second dimension would just be count($array[0]) if it's uniform.

Comments

3

A multi-dimensional array is simply an array of arrays -- it's not like you've blocked out a rectangular set of addresses; more like a train where each car can be stacked as high as you like.

As such, the "height" of the array, presumably, is the count of the currently largest array member. @phihag has given a great way to get that (max(array_map(count, $array2d))) but I just want to be sure you understand what it means. The max height of the various arrays within the parent array has no effect on the size or capacity of any given array member.

1 Comment

When we start to talk about 2D array's dimensions, I'd propose sticking with the mathematical equivalent of a matrix, where height -number of rows- is usually considered the first dimension and width -number of columns- the second one.
1
$max = 0;

foreach($array as $val){
 $max = (count($val)>$max?count($val):$max)
}

where $max is the count you are looking for

Comments

1

In my application I have used this approach.

$array = array();

$array[0][0] = "one";
$array[0][1] = "two";

$array[1][0] = "three";
$array[1][1] = "four";

for ($i=0; isset($array[$i][1]); $i++) {
    echo $array[$i][1];
}

output: twofour

Probably, this is not the best approach for your application, but for mine it worked perfectly.

Comments

0

To sum up the second dimension, use count in a loop:

$counter = 0;
foreach($var AS $value) {
    $counter += count($value);
}

echo $counter;

Comments

0

1.dimension:

count($arr);

2.dimension:

function count2($arr) {
  $dim = 0;

  foreach ($arr as $v) {
    if (count($v) > $dim)
      $dim = count($v);
  }

  return $dim;
}

As it is possible to have each array / vector of different length (unlike a mathematical matrix) you have to look for the max. length.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.