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? Commented Apr 25, 2015 at 11:25
  • why do you need of is_int? Commented Apr 25, 2015 at 11:26
  • 2
    display the output of var_dump($data) Commented Apr 25, 2015 at 11:27
  • how we fetch the data from database i mean a single row,a array or an object???? Commented 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. Commented 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
Sign up to request clarification or add additional context in comments.

Comments

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;

Comments

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 Comment

Floats are numeric, too

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.