John Davidson

php - Validating numeric values in a string. Why is this condition giving true?

0 comments
Message:


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();
}
}
}



My Answer:
= count($splt_data); $i++) {
if (is_numeric($splt_data[$i])) {
echo "true";
} else {
echo "false";
}
}

The problem with your code is that you are splitting the string into individual characters using str_split() function. This means that each character in the string will be treated as a separate element in the array $splt_data.

When you use is_numeric() function to check if a value is numeric, it will return true for any numeric character, not just for numbers. For example, is_numeric('5') will return true, but is_numeric('a') will also return true because 'a' is considered a numeric character.

If you want to check if the entire string contains only numeric values, you can use the following code:

$data = 'String';
if (is_numeric($data)) {
echo "true";
} else {
echo "false";
}

This will return false for the string 'String' because it contains non-numeric characters.

Rate this post

3 of 5 based on 5069 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us