1

I want to validate an array so only integer number is allowed. I've tried some ways but still doesn't get the result I want.

I have array like this:

array(5) { 
   [0]=> string(3) "312" 
   [1]=> string(2) "41" 
   [2]=> string(2) "44" 
   [3]=> string(2) "22" 
   [4]=> string(2) "22" 
}

First I'm writing a code like this:

$total= $_POST["total"];
if (!preg_match ("/^[0-9]*$/", $total) ) {  
        $ErrMsg = "Only numeric value is allowed.";
        echo $ErrMsg;
}

I got an error that said only string allowed for !preg_match function, this is because $total is an array.

Next is I'm trying to convert $total to a string.

$total= $_POST["total"];
$stringTotal = implode(", ", $total);
    
    if (!preg_match ("/^[0-9]*$/", $total) ) {  
        $ErrMsg = "Only numeric value is allowed.";
        echo $ErrMsg;

The code above no longer give error, but the result still wrong. $total is a string so the result will false.

Is there's any way how to do it? Thank you

3
  • 1
    After you implode, the string contains commas and spaces, so it doesn't match the regexp. Commented Aug 3, 2021 at 14:41
  • @Barmar what I need to do to to make it match? Commented Aug 3, 2021 at 14:45
  • implode('', $total) so no commas or spaces are included in the result. Commented Aug 3, 2021 at 14:48

1 Answer 1

2

You can loop through the array.

foreach ($total as $num) {
    if (!preg_match("/^[0-9]*$/", $num) ) {  
        $ErrMsg = "Only numeric value is allowed.";
        echo $ErrMsg;
        break;
    }
}

Note also that your regular expression matches an empty string and treats it as an integer. If you don't want to include that, change * to +.

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

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.