=== and ==

Ask about a PHP problem here.
Post Reply
jonathon
Posts: 50
Joined: Fri May 06, 2011 5:09 pm

=== and ==

Post by jonathon »

I was just using this code to validate a $_GET variable against a session user_id and I noticed that when I use the '===' it fails as if to say they are not equal but the '==' says they are equal. I know the difference between them but I don't understand why === fails. Does anybody know

[syntax=php]
if(isset($_GET['id']) && filter_var($_GET['id'], FILTER_VALIDATE_INT, array('min_range' => 1))) {

if(isset($_SESSION['user_id']) && ($_SESSION['user_id'] == $_GET['id'])) { // if session exists and is === $_GET['id']

// I'm just manually setting a session like this btw:
$_SESSION['user_id'] = 1;

[/syntax]

Thanks
libeco
Posts: 104
Joined: Sat May 07, 2011 9:56 am

Re: === and ==

Post by libeco »

The === checks for type too. It's possible that either the get or the session variable contains string data, while the other contains an integer. If you know which one to expect you can use typecasting to compare them:
[syntax=php](int)$_SESSION['user_id'] === (int)$_GET['id'][/syntax]
jonathon
Posts: 50
Joined: Fri May 06, 2011 5:09 pm

Re: === and ==

Post by jonathon »

Hi Libeco,

I know it checks the type which is why it confused me, I'm setting the $_SESSION which is in the code already posted and the $_GET['id'] is already validated to be an integer. So as they are not treated as the same if i use the (int) on them won't it just set the "non-integar" value to 0?
jonathon
Posts: 50
Joined: Fri May 06, 2011 5:09 pm

Re: === and ==

Post by jonathon »

No appears to be the answer using
[syntax=php]
if(isset($_SESSION['user_id']) && ((int)$_SESSION['user_id'] === (int)$_GET['id'])) { // if session exists and is === $_GET['id']
[/syntax]

Seems strange to me though - Thanks for your help.
libeco
Posts: 104
Joined: Sat May 07, 2011 9:56 am

Re: === and ==

Post by libeco »

Think about it this way: in the URL you have perhaps something like id=4. How will PHP know the type from that as it might aswell be id=e4. So it probably handles a get variable as a string.
Josh
Posts: 38
Joined: Tue Oct 11, 2011 9:31 pm

Re: === and ==

Post by Josh »

Let's say you had two variables: one is the integer 3 and the other is a string representation of the number 3, so it'd be "3" or '3'.
If you compared them two variables using == it would come out true, as they are equal, but if you use === it would return false because they are different types and that's the main difference, === checks types whereas == just checks values.
Post Reply