I'm fairly new to php and i have problem with loops. I have a foreach loop,
foreach ($contents as $g => $f)
{
p($f);
}
which gives some arrays, depending on how many contents i have. currently i have 2,
Array
(
[quantity] => 1
[discount] => 1
[discount_id] => 0
[id] => 1506
[cat_id] => 160
[price] => 89
[title] => კაბა
)
Array
(
[quantity] => 1
[discount] => 1
[discount_id] => 0
[id] => 1561
[cat_id] => 160
[price] => 79
[title] => ზედა
)
my goal is to save the array which has the max price in it as a different variable. I'm kinda stuck on how to do that, i managed to find the max price with the max()
function like so
foreach ($contents as $g => $f)
{
$priceprod[] = $f['price'];
$maxprice = max($priceprod);
p($maxprice);
}
but i still dont get how i'm supposed to find out in which array is the max price. any suggestions would be appreciated
You should store the keys as well so that you can look it up after the loop:
$priceprod = array();
foreach ($contents as $g => $f)
{
// use the key $g in the $priceprod array
$priceprod[$g] = $f['price'];
}
// get the highest price
$maxprice = max($priceprod);
// find the key of the product with the highest price
$product_key = array_search($maxprice, $priceprod);
$product_with_highest_price = $contents[$product_key];
Note that the results will be unreliable if there are multiple products with the same price.
Check max function for the array in outside the loop.
foreach ($contents as $g => $f)
{
$priceprod[] = $f['price'];
}
$maxprice = max($priceprod);
p($maxprice);
Here you got single loop solution handling multiple items with same max price.
$maxPrice = - INF;
$keys = [];
foreach($contents as $k=>$v){
if($v['price']>$maxPrice){
$maxPrice = $v['price'];
$keys = [$k];
}else if($v['price']==$maxPrice){
$keys[] = $k;
}
}