Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does casting a string as an integer not work?

Tags:

php

casting

int

// 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
like image 356
Patrick Moore Avatar asked Jan 20 '26 04:01

Patrick Moore


1 Answers

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
}
like image 170
Franz Gleichmann Avatar answered Jan 21 '26 23:01

Franz Gleichmann