Jump to content

php getting min values index


Paola

Recommended Posts


 

<?php


$a = array(-15, 3, 5, -1, -15);
$b = array(1, 3, 5);

function lowest_int ($c){

 
   print_r(array_keys($c, min($c)));
    
    

   }


print_r(lowest_int($a));
print_r(lowest_int($b));


?>

Hello guys the out of my code should be [0] => -15 [4] => -15 for the first array and [0] => 1 for the second array.
However. this is my output:

 

Array ( [0] => 1 [1] => 4 )

Array ( [0] => 0 )

 

Any ideas what am doing wrong? Thank you so much in advance!

Edited by Paola
Link to comment
Share on other sites

Having got the keys with the min value you then need to get those items from the original array

$a = array(-15, 3, 5, -1, -15);
$b = array(1, 3, 5);

function lowest_int ($c){
    $result = [];
    foreach (array_keys($c, min($c)) as $k) {
            $result[$k] = $c[$k];
    }
    return $result;    
}          

echo '<pre>';
print_r(lowest_int($a));
print_r(lowest_int($b));
echo '</pre>';

output

Array
(
    [0] => -15
    [4] => -15
)
Array
(
    [0] => 1
)

An alternative solution could be to use array_filter() in your function to remove items not equal to the minimum value

function lowest_int ($c){
      $min = min($c);
      return array_filter( $c, function($v) use($min) { return $v==$min; } );
}          

 

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.