1

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?

8
  • what is your id field in the DB? an integer or a varchar? Apr 25, 2015 at 11:25
  • why do you need of is_int? Apr 25, 2015 at 11:26
  • 2
    display the output of var_dump($data) Apr 25, 2015 at 11:27
  • how we fetch the data from database i mean a single row,a array or an object????
    – Saty
    Apr 25, 2015 at 11:28
  • 4
    I'm pretty sure that everything you get back from a database, are strings, but I cannot find any references. What database API are you using, PDO, mysqli, etc.? By the way, you could use is_numeric instead.
    – jeroen
    Apr 25, 2015 at 11:31

3 Answers 3

2

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
0

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;
0

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;
}
1
  • 1
    Floats are numeric, too Apr 25, 2015 at 11:33

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.