Help with comparing values, looping arrays

I am currently going to school for Web Design, and I am now in a PHP class, but I am having a problem understanding how to loop through an array while looking at a specific value, storing the values that are greater than the value in the first array, and ultimately displaying the name of the array that has the lowest value of them all. Here’s what I have done so far and where I’m not sure how to proceed:

[php]
// These are the arrays I’m working with.
$beverages = array(
array(
‘product’ => ‘Dr. Pepper’,
‘calories’ => ‘150’,
‘fat’ => ‘0’,
‘carbs’ => ‘40g’,
‘sodium’ => ‘55mg’,
‘sugar’ => ‘40g’
),
array(
‘product’ => ‘Coca-cola’,
‘calories’ => ‘140’,
‘fat’ => ‘0’,
‘carbs’ => ‘39g’,
‘sodium’ => ‘45mg’,
‘sugar’ => ‘39g’
),
array(
‘product’ => ‘Pepsi’,
‘calories’ => ‘150’,
‘fat’ => ‘0’,
‘carbs’ => ‘41g’,
‘sodium’ => ‘30mg’,
‘sugar’ => ‘41g’
),
array(
‘product’ => ‘Sprite’,
‘calories’ => ‘90’,
‘fat’ => ‘0’,
‘carbs’ => ‘24g’,
‘sodium’ => ‘40mg’,
‘sugar’ => ‘24g’
)
);

// The next thing I had to do was remove the ‘fat’ item from each array before I start the loop.
foreach($beverages as $key => $beverage) {
if($beverage[‘fat’] == 0){
unset($beverages[$key][‘fat’]);
}
}

echo ‘

’;
print_r($beverages);
echo ‘
’;

// The next thing I needed to do was to create a variable to store the value of ‘calories’ for the first array., and create a variable for ‘product’.
$calories = ‘calories’;
$name = ‘product’;

// Now this is where I’m unsure. I now need to loop through each array to see if the calories in the first array is lower than the calories in the current item that is being looped through. If the calories are lower, I need to store the amount of $calories for that product. Then store the name of the product in $name.
foreach ($beverages as $key => $calories) {
if ($value > $calories)
}

// After all that is done, I need to echo the product $name that has the lowest calories in the arrays.
echo ‘The lowest calorie product is ’ . $name . ’ with ’ . $calories . ’ calories.’;
[/php]
Everywhere I turned online, I kept seeing very specific examples, specifically pertaining to numbers and a single array, not arrays within an array, so hopefully someone here can help me figure out what I’m doing wrong, and if you can, please explain what I’ve done wrong so that I can understand it.

Well, first, when you remove an element from a nested array, you do not need to test for the key.
Therefore, this section:
[php]
// The next thing I had to do was remove the ‘fat’ item from each array before I start the loop.
foreach($beverages as $key => $beverage) {
if($beverage[‘fat’] == 0){
unset($beverages[$key][‘fat’]);
}
}
[/php]
Can be speeded up like this: (In the loop, you already know the key and column for ‘fat’!)
[php]
// The next thing I had to do was remove the ‘fat’ item from each array before I start the loop.
foreach($beverages as $key => $beverage) {
unset($beverages[$key][‘fat’]);
}
[/php]

Next, as long as you have PHP version 5.5 or higher, you can use one command to test for the lowest value
in a nested array column loosely like this: (Not tested as I currently have version 5.4)
[php]
$lowest_calories = min( array_column( $beverages, ‘calories’ ) );
echo ‘The lowest calorie product is ’ . $name . ’ with ’ . $beverages[$lowest_calories][$calories] . ’ calories.’;
[/php]
Or, with PHP version’s less than 5.5, you can use this code… (NOTE: I combined loops to save resources…)
[php]
$lowest_calories = 99999;
foreach($beverages as $key => $beverage) {
unset($beverages[$key][‘fat’]);
if ($beverage[“calories”]<$lowest_calories) {
$lowest_beverage = $key;
$lowest_calories = $beverage[“calories”];
}
}
echo ‘The lowest calorie product is ’ . $beverages[$lowest_beverage][“product”] . ’ with ’ . $beverages[$lowest_beverage][‘calories’] . ’ calories.’;

echo '<pre>';
print_r($beverages);
echo '</pre>';

[/php]
NOTE: As you see, I keep the calorie count, but, saved the key of the product with the lowest count. This does
save time, but, means you need to use the indexes when displaying the values in the nested array.
Hope this helps…

[php]
foreach($beverages as $key => $beverage) {
if($beverage[‘fat’] == 0){
unset($beverages[$key][‘fat’]);
}
}
[/php]

You are mixing the for/foreach loop syntaxes. Using a foreach this should be written like this:

[php]
foreach($beverages as $beverage) {
if($beverage[‘fat’] == 0){
unset($beverage[‘fat’]);
}
}
[/php]

Note that the $key => $value syntax is perfectly valid, but as we don’t need the key using the foreach we can just omit it (it defaults to the value)

Using a for loop this would look like this

[php]
for ($i = 0; $i < count($beverages); $i++) {
if($beverages[$i][‘fat’] == 0){
unset($beverages[$i][‘fat’]);
}
}
[/php]

Here you can see we need the iterator / key as we don’t get each “row” of the array as a new variable, like we do with the foreach loop.

[hr]

Using the foreach loop your original array is not changed - even though you unset $beverage[‘fat’]. This is because you get a new variable $beverage for each iteration, and that variable has no reference to the original array element.

Either change to use objects (as they are passed by reference by default) or tell PHP it should keep track of the reference.

[php]
foreach($beverages as &$beverage) {
if($beverage[‘fat’] == 0){
unset($beverage[‘fat’]);
}
}
[/php]

Using the & sign here will effectively result in you editing the original $beverage that’s in the $beverages array, instead of a new one.

This does not affect the for loop as in that case you’re using the index to directly access the array element you are working with.

I prefer the foreach loop for readability. I work with objects so I don’t have to consider the reference issue above.

[hr]

I changed this

[php]
$calories = ‘calories’;
$name = ‘product’;
[/php]

to this, comparing the calorie count of a bevarage to the string ‘calories’ doesn’t make sense. So this makes it more understandable

[php]
$calories = 0;
$name = ‘’;
[/php]

[php]
foreach ($beverages as $key => $calories) {
if ($value > $calories)
}
[/php]

First off we need to change the foreach to select each beverage from the array, then if the current beverage has more calories than our saved value (initially 0), we update the calorie and name variables

[php]
foreach ($beverages as $beverage) {
if ($beverage[‘calories’] > $calories) {
$name = $beverage[‘product’];
$calories = $beverage[‘calories’];
}
}
[/php]

I suggest changing this code to this instead:

[php]
// The next thing I needed to do was to create a variable to store the product with the most calories
$maxCalorieProduct = null;

foreach ($beverages as $beverage) {
if (!isset($maxCalorieProduct[‘calories’]) || $beverage[‘calories’] > $maxCalorieProduct[‘calories’]) {
$maxCalorieProduct = $beverage;
}
}

// After all that is done, I need to echo the product $name that has the lowest calories in the arrays.
echo ‘The lowest calorie product is ’ . $maxCalorieProduct[‘product’] . ’ with ’ . $maxCalorieProduct[‘calories’] . ’ calories.’;
[/php]

Everything has worked so far, except for the final echo statement. When I use this:
[php]
foreach ($beverages as $beverage) {
if ($beverage[‘calories’] > $calories) {
$name = $beverage[‘product’];
$calories = $beverage[‘calories’];
}
}
[/php]
I get an echo statement for “The lowest calorie product is with calories calories.”

So I switch it to:
[php]
foreach ($beverages as $beverage) {
if ($calories < $beverages[1]) {
$name = $beverage[‘product’];
$calories = $beverage[‘calories’];
}
}
[/php]
And that results in “The lowest calorie product is Sprite with 90 calories.” Now that is the correct answer, but now I need to be able to give a product lower than 90 calories and except the execution to then show THAT product as being the one with the lowest calories, but instead, it keeps giving me the same result. I thought if I flipped the < to > it would work, but it shows “The lowest calorie product is with calories calories.” So it seems that what I have written has gotten me a bit closer to what I’m looking for, now using these variables only (because I am not able to add anymore as you guys have suggested), I have to figure out how to make sure the arrays are looped through every time to find the product with the lowest calories so that product name and its calorie count is echoed at the end using:
[php]
echo ‘The lowest calorie product is ’ . $name . ’ with ’ . $calories . ’ calories.’;
[/php]
which I also cannot alter at all.

Well this:
if ($beverage[‘calories’] > $calories) {
And this:
if ($calories < $beverages[1]) {
Are nothing similar! Not at all…

The first check the current beverage’s calories field to see if it is larger than the saved $calories variable.
The second compares the saved $calories varible to the FIRST beverage in the $beverages array. (Note the “s”)
Therefore you are comparing the incorrect items…

Since you want the beverage with the largest calorie count and since the foreach loop sets the calories to the
current one if the compare is TRUE, you would need to see if the current value is higher (larger) than the saved
one. Also, you would have to start $calories at zero: $calories = 0; Then, use this for the compare:
if ($beverage[‘calories’] > $calories) {
As you had, but, you must reset the starting value of the $calories to a low value…

YES!! That was it! Thank you very much, I’ve been stuck on this for a few days and I wasn’t able to find help anywhere else!

Glad we could help you! I will mark this one solved…

If you get stuck with another puzzle, start a new post…

Congrats! Always nice to solve a programming puzzle…

I have a strong feeling I will be back with a new thread.

Sponsor our Newsletter | Privacy Policy | Terms of Service