0

I currently have a form containing an input:

<input type="text" name="score" id="score" value="" />

Criteria: I need the value in this input to be below 40 and a positive integer or zero.

Having read up on php.net about is_int() and is_numeric(). It advises using is_numeric() with form fields as these are always numeric strings.

I want to check if the value meets the above criteria but don't follow how I would do this in the above situation.

<?php
$score = $_POST['score'];
if(is_numeric($score) && $score <= 40){
    // Do good stuff
} else {
  // Don't do good stuff
} ?>

My issue with the above is that floats would pass this test and without using something like (int) $score I can't use is_int() which then negates the is_numeric check.

Am I missing something here?

5
  • Why not check with is_numeric and then cast to int? Commented Jun 10, 2014 at 14:02
  • I don't want to change the input they gave so if they gave me 32.5 then I want to give that back it as the same value in the error Commented Jun 10, 2014 at 14:04
  • @timothystringer Then why do you need to validate if it's an integer more over whether it was a string,float,hex etc? Commented Jun 10, 2014 at 14:06
  • Try this Commented Jun 10, 2014 at 14:07
  • @DarylGill because it's a test result which only gets whole number scores so I need to make sure that's all I'm accepting Commented Jun 10, 2014 at 14:09

2 Answers 2

0

Use ctype_digit() to make sure the string consists only of numbers, and therefore is an integer - technically, this returns true also with very large numbers that are beyond int's scope. Note that this method will not recognize negative numbers.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this looks like it may be what I need
0
<?php
$score = $_POST['score'];
if(ctype_digit($score) && $score <= 40){
    // Do good stuff
} else {
  // Don't do good stuff
} 
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.