0

Input validation above loop works just fine, but not working in loop. Input should not allow: string and negative numbers. Any workaround to do this or just using inside loop is not a go? Yes, I know the maximum entered number can be checked in other ways, but I'm interested in this particular case with "for loop".

$amount = readline("Enter amount of inputs: ");
if (!is_numeric($amount) || !(0 < $amount)){
    echo "Invalid input";
    exit;
}
$numbers = [];

for ($i = 1; $i <= $amount; $i++){
    $numbers[] = readline("Input number {$i}: ");
    if (!is_numeric($amount) || !(0 < $amount)){
        echo "Invalid input";
        exit;
    }
}

$largestNumbers = max($numbers);
$numbersList = implode(",", $numbers);

echo "The largest number of $numbersList is $largestNumbers";
Goaul
  • 943
  • 11
  • 13

1 Answers1

1

Why are you checking $amount in the loop, you are reading into $numbers? And since you're reading into an array you'll need to specify the index:

for ($i = 1; $i <= $amount; $i++){
    $numbers[$i] = readline("Input number {$i}: ");
    if (!is_numeric($numbers[$i]) || !(0 < $numbers[$i])){
        echo "Invalid input";
        exit;
    }
}

I might use ($numbers[$i] <= 0) instead.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • Ah sorry, that `$amount` was copy paste error before posting, but the `[i]` is good one, thnx – Goaul Aug 25 '21 at 04:38