Home > Net >  How to count the total digit/numbers, the odd numbers and even numbers respectively in a php loop
How to count the total digit/numbers, the odd numbers and even numbers respectively in a php loop

Time:03-18

I want to count the total numbers in the pyramid loop and I want to count all the odd and even numbers respectively. There is a problem in my code where odd and even numbers are incorrectly counted.

The result should be:

Total numbers:

Total odd numbers:

Total Even numbers:

<?php


if (isset($_POST['btnsend'])) {
$oddCount = 0;
$evenCount = 0;

$num = $_POST['number'];
$width = strlen($_POST['number'])   1;
for ($row = 1; $row <= $num; $row  ) {
    if ($ % 2 == 0) 
        $evenCount  ;
    else
        $oddCount  ;
    echo "<div style='display: flex; justify-content: center; text-align: center;'>";
    for ($x = 1; $x <= $row; $x  ) {
        echo "<div style='width: {$width}ch; background: green;'>$row&nbsp;&nbsp;</div>";
    }
    echo "</div>";
}


echo "<p>You have {$evenCount} even and {$oddCount} odd numbers</p>";

}

CodePudding user response:

I think you should have been able to work this out yourself. It is not a difficult problem. Learning to program is learning to solve problems. If you keep asking other people to solve your problems, you're not learning yourself.

That being said, I think what you want is this:

<?php

$userInput = 5;
$oddCount  = 0;
$evenCount = 0;

$num = $userInput;
$width = strlen($num)   1;
for ($row = 1; $row <= $num; $row  ) {
    if ($row % 2 == 0) {
        $evenCount  = $row;
    } else {
        $oddCount  = $row;
    }    
    echo "<div style='display: flex; justify-content: center; text-align: center;'>";
    for ($x = 1; $x <= $row; $x  ) {
        echo "<div style='width: {$width}ch; background: green;'>$row&nbsp;&nbsp;</div>";
    }
    echo "</div>";
}

echo "<p>You have {$evenCount} even and {$oddCount} odd numbers</p>";

I had to remove the $_POST because I don't have your form. For the input of 5 this returns:

You have 6 even and 9 odd numbers

Change the input to 10 and you get:

You have 30 even and 25 odd numbers

As you can see it's not difficult to do.

  • Related