Forum > PHP Code Discussion

Variable Assignment Through URL w/ Default Value

(1/1)

Ianedres:
I wrote this function to check for a setting in the URL string, and if not present, assign a default value to it. This was for dynamic control of the page, where I could pass changes through the URL.


--- Code: ---function check($value, $default)
{
if(empty($value)) $value = $default;
return($value);
}
--- End code ---

Usage in the script itself is one single line of:


--- Code: ---$height = check($_GET['height'], '512');
--- End code ---

The variable $height will be assigned the value returned by the function. When called, the function is passed two parameters; the first is the setting in the URL (?height=xx) through the GET function, and the second is a default value of '512'.

Inside the function, if the first value is empty (no value if not specified in the URL), then the function will use the default value; otherwise, the non-empty value is used.

The function then returns that value back the script, where it is assigned to the variable $height.

Basically, it eliminated the need to redundantly code something like this for each additional variable:


--- Code: ---$variable2 = $_GET['variable2'];
if empty($variable2) $variable2 = 'defaultvalue';
--- End code ---

Not exactly ground-breaking, but helped me reduce the possibility of some typos in error-checking each variable as it is set. Additionally, you could check the value in the function for the type of value (numeric, string, etc) to prevent other errors...

IchBin™:
Very cool. This is the type of things PHP coders love. Automate anything that you can. :)

Ianedres:
It served multiple purposes for me in this script, and I'll use something similar in other scripts as it comes along.

Main thing is that if you are parsing through one or two variables, it isn't worth the trouble- but if you have more than that then it would be. Plus, you can standardize your variable checking in one place.

Smoky:
that is pretty kewl Ianedres.. so if i had say 10 url's i could get them to either go default, or have them say, alternate.. i like that.. just not sure yet where i would use it, but at least i think i understand..  :afro:

Ianedres:
The function is a small part of a dynamic script; calling the URL with certain variables (or not at all) could allow the script to function correctly regardless.

Basically, I used it to be able to set the display size of an image (actually, a Google-powered map) at one size in a page, but provide a link to display the same image (using the exact same script  :afro:) in a new window but much larger.

Of course, this could be adapted for any variable to be changed through the URL passed to the script.

Navigation

[0] Message Index

Go to full version