Skip to content
Advertisement

Validating array only integer number in PHP

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

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement