phpvariablesquery-stringdefault-valueisset

Declare variable from value in query string of url and fallback to a default value if missing


I have a variable, $id, which identifies the product category type to display on the page. I first need to check that the id variable has been set and if not, default the variable to category 0.

The code I have is as follows:

setdefault($id, 0);

function setdefault(&$var, $default="") 
{
   if (!isset($var)) 
   {
      $var = $default;
   }
}

So with the address www.website.com/browse.php, I would expect it to default to $id = 0.

With the address www.website.com/browse.php?id=3, I would expect it to set $id = 3 and display the relevant products.

However, despite setting $id, it still defaults to 0. Is there something obviously incorrect with my code?


Solution

  • You are probably expecting PHP to use the $_POST and $_GET as global variables. PHP used to be setup this way, back in the day, but newer versions require you to explicitly reference these variables.

    You could try this:

    setdefault($_GET['id'], 0);
    
    function setdefault(&$var, $default="") 
    {
       if (!isset($var)) 
       {
          $var = $default;
       }
    }
    

    or even more simply (using the ternary operator):

    $id = array_key_exists('id', $_GET) ? $_GET['id'] : 0;