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”.
This entry was posted on Tuesday, July 15th, 2008 at 7:35 am and is filed under PHP. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.


or more simbel :)
function getUrlStrVal($key, $default = ”){
return isset($_GET[$key]) && $_GET[$key] != ” ? $_GET[$key] : $default;
}
July 16th, 2008 at 12:27 am