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;
}
2
Answers
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:
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:Demo on 3v4l.org
Note that the
break
in theif
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.