An array of C#, PHP, and HTML programming articles, tutorials, and resources

Posts Tagged ‘ get ’

One of my favorite and most heavily used PHP common functions retrieves variables from the query string. I found that without this function, I was inefficiently checking if the variable existed, and if not, I was then was manually setting a default value. The function takes in two string variables that handle the above problem. $urlStringName is the name of the variable as stated in the query string and $returnIfNotSet is the string that will be returned if the $urlStringName is not found. Check out the code snippet below:

function getUrlStringValue($urlStringName, $returnIfNotSet) {
  if(isset($_GET[$urlStringName]) && $_GET[$urlStringName] != "")
    return $_GET[$urlStringName];
  else
    return $returnIfNotSet;
}

Let’s run through an example of how this function works. Assume we have the following url:

http://www.victorchen.info/index.php?firstName=Victor&lastName=Chen

If I am looking to find the string value of the first and last name, but return john or doe if the query variable firstName or lastName is not found, respectively. I would write the following:

$firstName = getUrlStringValue("firstName", "john");
$lastName = getUrlStringValue("lastName", "doe");

In this example, we would expect to store $firstName to be “Victor” and $lastName to be “Chen”.

However, if the url arrives as (missing the lastName query string variable):

http://www.victorchen.info/index.php?firstName=Victor

We can expect to see $firstName as “Victor” and $lastName as “Doe”.