3
votes

// 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
2
when you compare with ==, values are implicitely cast. it's the same as (int)$val == (int)$val. thing is: what are you even trying to achieve with your code? - Franz Gleichmann
@FranzGleichmann thanks for this. User can pass a record ID (integer) or a name (string). I build a MySQL query depending on whether it's integer (user_id = $val) or whether it's string (user_name LIKE '%val%'`) - Patrick Moore
Yeah, shouldn't ($val == (int)$val) be ($val = (int)$val) ? or are you trying to use a ternary operator here? - Funk Forty Niner
I use if (is_numeric($searchval)) when I do a string or ID entry search. - IncredibleHat
@PatrickMoore use is_numeric for this. - Franz Gleichmann

2 Answers

3
votes

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
}
3
votes

To check whether string is actually a number, I'd use something like that:

if (strval(intval($val, 10)) == $val)

Note: this will detect only strings with integer numbers, there is also is_numeric which works for decimal and exponential (like +0123.45e6).

Note 2: is_int detects actual type of variable, so for "123" it will return false because it is string.

Note 3: you could have problems when number is submitted with + prefix like +123 - it is up to you whether you want to support such case or not