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.

Link to comment
Share on other sites

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?

Link to comment
Share on other sites

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. :)

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.