Is this normal?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
lafever
Forum Commoner
Posts: 99
Joined: Sat Apr 05, 2008 2:03 pm
Location: Taylor, MI

Is this normal?

Post 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?
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: Is this normal?

Post 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']);
There are 10 types of people in this world, those who understand binary and those who don't
User avatar
Zoxive
Forum Regular
Posts: 974
Joined: Fri Apr 01, 2005 4:37 pm
Location: Bay City, Michigan

Re: Is this normal?

Post 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)
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Re: Is this normal?

Post by RobertGonzalez »

is_numeric() FTW. It checks value not type.
User avatar
lafever
Forum Commoner
Posts: 99
Joined: Sat Apr 05, 2008 2:03 pm
Location: Taylor, MI

Re: Is this normal?

Post by lafever »

Ahh... guess I should have paid more close attention to the manual. :banghead:
Post Reply