Jump to content

[SOLVED] array max location


asmith

Recommended Posts

mm i search the php.net for in_array  , found nothing special there , but i found  array_search function .

with array search i can find its key , but it shows the first one for duplicate values !

any idea ? 

 

 


<?php

$a= array(1,5,7,8,8,;

$b = array_search(8,$a);

echo $b;

?>

 

the code echos 3 . 

 

I don't believe there is a built-in function to do what you want, you can write one:

<?php
function get_maxs($ary) {
  $max = max($ary);
  $tmp = array();
  for ($i=0;$i<count($ary);$i++)
     if ($ary[$i] == $max) $tmp[] = $i;
  return ($tmp);
}

$test = array(1,5,3,6,3,6,8,6,6,6);
echo '<pre>' . print_r(get_maxs($test,true)) . '</pre>';
?>

 

Ken

Let's try a loop...

 

<?php
$a = array ( 1, 4, 6, 3, 6, 1, 6 );
echo "<pre>";
print_r($a);
echo "</pre><br>";
$arrayMax = max($a);
$found = array();
foreach ( $a as $key => $value ) {
   if ( $value == $arrayMax ) {
       $found[$key] = $value;
   }
}
echo 'I found the largest value was ' . $arrayMax . ', and it appeared in the following keys of $a[]:<br>';
foreach ( $found as $key => $value ) {
   echo $key . ' => ' . $value . '<br>';
}

 

Output:

 

Array
(
   [0] => 1
   [1] => 4
   [2] => 6
   [3] => 3
   [4] => 6
   [5] => 1
   [6] => 6
)


I found the largest value was 6, and it appeared in the following keys of $a[]:
2 => 6
4 => 6
6 => 6

 

PhREEEk

Here's my fixed function:

<?php
function get_maxs($ary) {
  print_r($ary);
  $max = max($ary);
  $tmp = array();
  for ($i=0;$i<count($ary);$i++) {
     if ($ary[$i] == $max) {
        $tmp[] = $i;
        echo $i . ' ... ' . $ary[$i] . ' ... ' . $max . "\n";
        }
  }
  return ($tmp);
}

$test = array(1,5,3,6,3,6,5,6,6,6);
$x = get_maxs($test);
echo '<pre>' . print_r($x,true) . '</pre>';
?>

 

Ken

PHP has a built in function for returning the keys a value is stored within the array. So need for any loops. Just two function calls max and array_keys:

<?php

$a = array ( 1, 4, 6, 3, 6, 1, 6 );

echo '<pre>' . print_r($a, true) . '</pre>';

$max  = max($a);              // get the max value in an array
$keys = array_keys($a, $max); // return the keys for the max value

echo 'Max value: ' . $max . "<br />\nFound in Keys:<ul>\n<li>" . implode("</li>\n<li>", $keys) . '</li></ul>';

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.