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

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.