Reputation: 142
I have written a simple sql query and is_int() returns alway false. why?
mysql query
$sql = "SELECT id, username FROM users WHERE email = '[email protected]' LIMIT 1";
$data = $db->query($sql);
# output: php array like $data[0]['id'];
php if
if( is_int($data[0]['id'] ){
print 1;
}else{
print 0;
}
// edit var_dump print this:
array(2) { ["id"]=> string(1) "1" ["username"]=> string(6) "admin" }
Why is 'id' a string and not a integer?
Upvotes: 1
Views: 495
Reputation: 1795
I guess that the type of your variable is string. In your case is a good idea to use is_numeric()
If you expect to have some float values you may use is_float() as well:
if( is_numeric($data[0]['id']) && !is_float($data[0]['id']) ){
print 1;
}else{
print 0;
}
Upvotes: 0
Reputation: 9782
In case of string value is_int()
always return false.
is_int('23') = bool(false)
and according to comments you have ID as string
array(2) {
["id"]=> string(1) "1"
["username"]=> string(6) "admin"
}
So its always return false
Do it like :
if( is_array($data) && $data[0]['id'] > 0 ) {
print 1;
}
else print 0;
Upvotes: 0
Reputation: 355
How can an "id" be not an integer?
If you want to check the value:
<?php
function is_int_val($val) {
return $val == (string)((int)$val);
}
echo (is_int_val(33) ? "true" : "false")."\n"; // returns true
echo (is_int_val("33") ? "true" : "false")."\n"; // returns true
echo (is_int_val("33.0") ? "true" : "false")."\n"; // returns true
echo (is_int_val("a33") ? "true" : "false")."\n"; // returns false
echo (is_int_val("33a") ? "true" : "false")."\n"; // returns false
Upvotes: 2