Page 1 of 1

Is this normal?

Posted: Tue Apr 29, 2008 6:27 am
by lafever
So I was playing around with some session variables today and was coming across an error.

I was using

Code: Select all

 
<?php
$_SESSION['id'] = $row['id'];
 
echo $_SESSION['id']; // returned: 1
$id = $_SESSION['id'];
if (is_int($id)) {
  echo $id.' is an integer';
} else {
  echo $id.' is not an integer';
}
?>
 
This code was always returning false and saying it wasn't an integer. So then I tried the following, which properly worked.

Code: Select all

 
$_SESSION['id'] = $row['id'];
 
echo $_SESSION['id']; // returned: 1
$id = $_SESSION['id'];
if ((int)$id == $id) {
  echo $id.' is an integer';
} else {
  echo $id.' is not an integer';
}
?>
 
Is there a reason why the is_int() function wasn't working as expected? Is the $_SESSION returning this as some sort of string with the way I was doing it or something? My guess is yes, but why does just the simple echo of the $_SESSION return an integer then?

Re: Is this normal?

Posted: Tue Apr 29, 2008 6:47 am
by VladSun
RTM http://php.net/is_int
is_int — Find whether the type of a variable is integer
It's the type checked, not the value...

You may want to use:

Code: Select all

$_SESSION['id'] = intval($row['id']);

Re: Is this normal?

Posted: Tue Apr 29, 2008 10:32 am
by Zoxive
is_numeric() might be of use.

You can also use var_dump to see what type it really is.

Code: Select all

$one = "1"; //string
$two = 1; //integer
if ($one === $two) {
  echo 'one and two the same and the same type';
}elseif($one == $two){
  echo 'one and two are the same';
}else{
  echo "Not the same";
}
var_dump($one);
var_dump($two);
Result:

Code: Select all

one and two are the same
 
string(1) "1"
int(1)

Re: Is this normal?

Posted: Tue Apr 29, 2008 1:53 pm
by RobertGonzalez
is_numeric() FTW. It checks value not type.

Re: Is this normal?

Posted: Tue Apr 29, 2008 3:16 pm
by lafever
Ahh... guess I should have paid more close attention to the manual. :banghead: