phpconsole.readline

validate readline input (CLI) inside for loop


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

Solution

  • 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.