Jump to content
Paola

php getting min values index

Recommended Posts

Posted (edited)

 

<?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

Share this post


Link to post
Share on other sites

Have your function return the keys instead of printing them, then print the function results

function lowest_int ($c){
   return array_keys($c, min($c));
}

 

Share this post


Link to post
Share on other sites

Thank you for your input. I still get the same result.

Share this post


Link to post
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; } );
}          

 

Share this post


Link to post
Share on other sites

Thank you so much. That fixed my issue. I still want to research why my results were so off and with new number =(

 

Thank you again 😃

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×

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.