Help with finding the min values in an array

#1
<?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!

#2

You can use this link https://www.php.net/manual/en/function.min.php for your reference

#3

Thank you. I have been looking at the documentation but I do not see anything on why my arrays is changing values.

#4

have you tried using array_filter?

<?php
  $a = array(-15, 3, 5, -1, -15);

  //use anonymous function to return negative numbers using array_filter
  $negative = array_filter($a, function($number) {
      return $number < 0;
  });

  print_r($negative);
?>

this works for me with php 7+
#5

Thank you. That helped me a lot. I still wonder why my results were so off and I got even new numbers that were not in my array =(

Thank you so much!

#6

because array keys 0 and 4 have the lowest numbers -15
you are expecting values but specifying keys (array_keys)

to see just a single value:

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

to see the array plus the minimum number:

print_r(array($a, min($a)));
#7

That makes sense. Thank you so much for all you help :slightly_smiling_face:

1 Like
#8

I’m happy that i could help you with this problem.
I hope that you have a good day.