2

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

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

just what i needed, thanks a lot. will find a solution to same prices later probably. thanks
1

Check max function for the array in outside the loop.

foreach ($contents as $g => $f)
{

    $priceprod[] = $f['price'];

}
$maxprice = max($priceprod);
p($maxprice);

2 Comments

I think I asked my question wrong, the goal is to save the array which has max price in it as a different variable for later use.
What is p() at p($maxprice)?
0

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;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.