Wael Assaf Wael Assaf -4 years ago 136
PHP Question

How can i find out how many times a loop was executed in each if condition inside foreach loop?

Hey guys i need your help with this exercise.

I have this array and i need to print out each Positive, Negative, Zero number and then after that i need to print out the number of the numbers in each process for example the positive numbers count is 2

Can you help me please to do that ?

Full Code :



<style>
body {
background: #333;
}
</style>

<?php

$numbers = [10, 20, -20, -30, 0, 0, 0];
echo "<ul>";

foreach ($numbers as $number) {
if ($number > 0) {
echo "<li style='color: #080;'>Positive Number : {$number}</li><br />";
} elseif ($number == 0) {
echo "<li style='color: #FF0;'>Zero Number : {$number}</li><br />";
} elseif ($number) {
echo "<li style='color: #F00;'>Negative Number : {$number}</li><br />";
}
}
echo "</ul>";





Thanks guys

Answer Source

You have to declare counter variables and increment them inside your if conditions.

<style>
    body {
        background: #333;
    }
</style>

<?php

$numbers = [10, 20, -20, -30, 0, 0, 0];
echo "<ul>";

$positiveNumbers = 0;
$negativeNumbers = 0;
$zeros = 0;

foreach ($numbers as $number) {
    if ($number > 0) {
        $positiveNumbers++;
        echo "<li style='color: #080;'>Positive Number :  {$number}</li><br />";
    } elseif ($number == 0) {
        $zeros++;
        echo "<li style='color: #FF0;'>Zero Number :  {$number}</li><br />";
    } else {
        $negativeNumbers++;
        echo "<li style='color: #F00;'>Negative Number :  {$number}</li><br />";
    }
}
echo "</ul>";
echo "Total Positive Numbers: $positiveNumbers<br/>";
echo "Total Negative Numbers: $negativeNumbers<br/>";
echo "Total Zeroes: $zeros<br/>";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download