mk_89
mk_89

Reputation: 2742

returning the min array value index

I Am trying to compare 3 different array prices in order to find the lowest so that I can decide which array values should be input into a database, the code looks something like this at the moment...

$array_a = array(
   "id"    => 398,
   "price" => 100 
);

$array_b = array(
   "id"    => 387,
   "price" => 60
);

$array_c = array(
   "id"    => 127,
   "price" => 50
);

if($array_a && $array_b && $array_c){
   $newArr = array($array_a['price'], $array_b['price'], $array_c['price']);
   array_keys($newArr, min($newArr));
   print_r($newArr)."\n"; 
}

The above code does not return the correct index of the array with the lowest price which in this case would be 2 (array_c), what would be the correct way to find out the key of the lowest value.

Also what would be the best way to make sure that only numbers are compared with the min() function as opposed to strings?

Upvotes: 0

Views: 1575

Answers (4)

Jon
Jon

Reputation: 437664

You can automate it for example in this manner:

$newArr = array($array_a['price'], $array_b['price'], $array_c['price']);
asort($newArr, SORT_NUMERIC);
echo "Minimum: ".reset($newArr).", given in array #".key($newArr);

I 'm not so sure how to answer your closing question -- what should happen if the values are not actually typed as numbers?

Update: Here's one way to exclude non-numeric values:

asort($newArr, SORT_NUMERIC);
while (!is_numeric(current($newArr))) next($newArr);
if (key($newArr) === null) {
    echo "No valid elements found";
}
else {
    echo "Minimum: ".current($newArr).", given in array #".key($newArr);
}

Upvotes: 1

chokrijobs
chokrijobs

Reputation: 761

<?php
$array_a = array(
   "id"    => 398,
   "price" => 100 
);

$array_b = array(
   "id"    => 387,
   "price" => 60
);

$array_c = array(
   "id"    => 127,
   "price" => 50
);

if($array_a && $array_b && $array_c){
   $newArr = array($array_a['price'], $array_b['price'], $array_c['price']);
   $key_min = array_keys($newArr, min($newArr));
   echo $key_min[0];

}
?>

Upvotes: 1

thobens
thobens

Reputation: 1731

Try this:

$keys = array_keys($your_array);
asort($keys);
$min = $keys[0];
echo "Smallest index: ".$min;

Upvotes: 1

You can do:

$newArr = array($array_a['price'], $array_b['price'], $array_c['price']);
sort($newArr);
$lowest = array_shift($newArr);

Upvotes: 1

Related Questions