Retreive index of multi dimensional array

Hi,

I have a multidimensional array like
0 1 2 3 4
2 1.5 0 2.3
3 4 5 6
1 2 3 4

i need to find max of each row of this array and retreive corresponding index of the array where this max value is obtained

I found the max value but could not fetch the index. how could i fetch column index of particular row where this max value is found. Could you please advice.

i have posted the code for finding max.

for($row=0;$row<count($my_array);$row++)
{
	$max=$my_array[$row][0];
	for($col=1;$col<count($my_array[$row]);$col++)
	{

	if ($my_array[$row][$col] > $max )
	{
	     $max= $my_array[$row][$col];

	}
		
	
}
	echo $max."<br>" //this gives max value

//upto max is correct but i am stuck on index fetching 
while($element=each($my_array[$row])
{
    if($element['value']==$max)
{

echo $element['key'];
}
}

$a=array(
  array(0, 1  , 2, 3  ,  4),
  array(2, 1.5, 0, 2.3    ),
  array(3, 4  , 5, 6      ),
  array(1, 2  , 3, 4      )
);

$maxValues=array();
foreach($a as $row)
{
  $max=max($row);
  $maxIdx=array_search($max, $row);
  array_push(
    $maxValues,
    array('max'=>$max, 'index'=>$maxIdx)
  );
}

var_dump($maxValues);

/**


array(4) {
  [0]=>
  array(2) {
    ["max"]=>
    int(4)
    ["index"]=>
    int(4)
  }
  [1]=>
  array(2) {
    ["max"]=>
    float(2.3)
    ["index"]=>
    int(3)
  }
  [2]=>
  array(2) {
    ["max"]=>
    int(6)
    ["index"]=>
    int(3)
  }
  [3]=>
  array(2) {
    ["max"]=>
    int(4)
    ["index"]=>
    int(3)
  }
}
**/

It’s a bit poor man style and I don’t recommend using it on very large arrays, but for arrays like this it’s perfectly fine :slight_smile:

The only slight change to that solution I’d make is using the $index from foreach to maintain the relationship between the 2 arrays.


<?php
$array = array(
  array(0, 1  , 2, 3  ,  4),
  array(2, 1.5, 0, 2.3    ),
  array(3, 4  , 5, 6      ),
  array(1, 2  , 3, 4      )
);

$max = array();

foreach($array as $index => $set){
  $max[$index] = array(
    'index' => array_search(max($set), $set),
    'value' => max($set)
  );
}

var_dump(
  $max
);

/*
  array(4) {
    [0]=>
    array(2) {
      ["index"]=>
      int(4)
      ["value"]=>
      int(4)
    }
    [1]=>
    array(2) {
      ["index"]=>
      int(3)
      ["value"]=>
      float(2.3)
    }
    [2]=>
    array(2) {
      ["index"]=>
      int(3)
      ["value"]=>
      int(6)
    }
    [3]=>
    array(2) {
      ["index"]=>
      int(3)
      ["value"]=>
      int(4)
    }
  }
*/

It would come in handy if you have an oddly indexed source array…


$array = array(
  4  => array(0, 1  , 2, 3  ,  4),
  3  => array(2, 1.5, 0, 2.3    ),
  11 => array(3, 4  , 5, 6      ),
  0  => array(1, 2  , 3, 4      )
);

Thanks Scallio!! great it worked…

Off Topic:

It still amuses me how folk are amazed the solutions that are posted actually work; I guess they just assume they are untested. Maybe in other forums that is true, maybe we’re too nice here at SP. :stuck_out_tongue: