Jump to content

How do I treat a query-string as an integer?


Crono

Recommended Posts

Hi,

 

When I run the following code...

 

<?php

if ($_GET['view'])
{
    echo 'test';
}

 

.. and then navigate to index.php?view=1 the above code outputs 'test', as intended.

 

The same goes for any non-zero value after the ?view=

 

However, navigating to index.php?view=0 does not work as intended because it assumes that the 0 is FALSE.

 

So if I modify the code, like this:

 

<?php

if ($_GET['view'] || $_GET['view'] == 0)
{
    echo 'test';
}

 

... it outputs 'test' even when view is not set, i.e. when I navigate to index.php without the ?view=.

 

Is there an easy way to force the value to behave as an integer instead of boolean? I have tried putting (int) before, as well as the intval() function, but neither seem to work.

 

Thanks.

It will be coerced to a boolean value because that is what if statements run on. There is no way to change the functionality of an if statement, but I'm curious, what are you trying to do here? Based on that if statement, you can just use if (true) and get the same result? A some what hackish way of doing what you want would be

 


if (($_GET['view'] || $_GET['view'] == 0) && isset($_GET['view']))

 

But.. I'm still unsure of why you are even doing this. $_GET['view'] can be anything (except for the empty string) and that if statement would be true.. What exactly are you trying to test in this if statement?

I was making a little comment system whereby navigating to index.php?view=4, where 4 is the comment id, shows you that comment only (basically a permalink), but it didn't seem to work when the comment id was 0.

 

Your code seems to have fixed that -- thanks for your help. :)

In addition to what mikesta posted, one of these should do what you need also.

 

if( isset($_GET['view']) && ctype_digit($_GET['view']) ) { // will not accept negative values
if( isset($_GET['view']) && ctype_digit(str_replace('-', '', $_GET['view'])) ) { // will accept negative values

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.