Home > database >  Validating numeric values in a string. Why is this condition giving true?
Validating numeric values in a string. Why is this condition giving true?

Time:08-31

I'm trying to validate string to check is there any numeric value.. but the condition is not giving me expected result. What's the problem ?

$data = 'String';

$splt_data = str_split($data);
print_r($splt_data);

for ($i = 0; $i < count($splt_data); $i  ) {
    for ($x = 0; $x < 10; $x  ) {
        if ($splt_data[$i] == $x) {
            echo "<br> The \"$data\" value is containing numeric value.";
            echo "<br>" . $splt_data[$i] . ' and ' . $x;
            exit();
        }
    }
}

Output

CodePudding user response:

If you don't care about splitting the string and comparing each character, you could use a regex to see if there are any digits in the string:

$data = "String";

if(preg_match("/\\d/", $data)){
    // contains a digit
}

CodePudding user response:

So you are trying to find if the string has any numeric characters?

$result= preg_replace('/\D/','',$data);
if(strlen($result) > 0){echo 'WARNING: We got numeric infiltrators on our hands';}

Some times if you are expecting an integer value and need to validate it is an integer, just use

 $value = intval($data);

I always try to only pass numeric values. So most of my post values I do this: $zip = intval($_POST['zip']);

Phone numbers.

$phone = intval(preg_replace('/\D/','',$phone));
  • Related