Home > Blockchain >  I am trying to change my if statement to a for loop using php
I am trying to change my if statement to a for loop using php

Time:10-13

Basically I want to validate user input to ensure they are entering integer values. My if statement works well but my assignment is to change it to a for loop. Thanks!

my original if statement;

if (empty($scores[0]) ||
    empty($scores[1]) ||
    empty($scores[2]) ||
    !is_numeric($scores[0]) ||
    !is_numeric($scores[1]) ||
    !is_numeric($scores[2])) {
        $scores_string = 'You must enter three valid numbers for scores.';
        break;
}

CodePudding user response:

If you must use a for loop to validate the scores, then you just need to test each value in the $scores array in it:

$scores_string = '';
$len = count($scores);
for ($i = 0; $i < $len; $i  ) {
    if (empty($scores[$i]) || !is_numeric($scores[$i])) {
        $scores_string = 'You must enter three valid numbers for scores.';
        break;
    }
}
if ($scores_string != '') {
    echo $scores_string;
    // do anything else you need
}
else {
    // all is OK!
}

Demo on 3v4l.org

Note that the break in the if after you assign $scores_string saves iterating the entire array after a non-numeric value was found. If you wanted to count the number of non-numeric values, you'd increment a counter there instead.

CodePudding user response:

It's better to define a function that returns a boolean to validate the parameters. If one variable of the parameters is invalid, return false immediately. Otherwise, return true.

Then use the function directly.

Check out the code below:

function isNumberScores($scores) {
    foreach($socres as $score) {
        if (empty($score) || !is_numeric($score)) {
            return false
        }
    }
    return true
}

if (!isNumberScores($socres)) {
    $scores_string = 'You must enter three valid numbers for scores.';
    // your code here
}
  • Related