// EDIT: The end goal is to detect whether user-submitted value is a string, or an integer. Because the value is obtained from form input, it is cast as string even when the value provided is an integer number.
I am performing a simple comparison to detect if a string variable is equal to its integer value. The value is passed from an HTML form field.
When the string value is a single letter, it evaluates to true, when it should not.
if ( ($val == (int)$val ) && strlen( $val ) == strlen( (int)$val ) ){
}
I've also tried using intval() rather than casting int variable type.
It is always evaluating as true. But r does not == 0, so how can this be?
$val = 'r';
echo 'Does $val = (int)$val? ' . ($val == (int)$val);
echo '<br/><br/>';
echo '$val was: ' . $val . '<br/>';
echo '(int)$val was: ' . (int)$val;
Output:
Does $val = (int)$val? 1
$val was: r
(int)$val was: 0
To check if your string is actually a number (which is what you want according to your comments), you don't have to hack together some custom test. PHP provides a built-in function for this:
if(is_numeric($val)) {
//do integer stuff
} else {
//do string stuff
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With