[thelist] [php] Using the OR operator in an IF statement

Keith Gaughan keith at digital-crew.com
Mon Jan 10 10:38:18 CST 2005


Help Center Live - Mike wrote:

> I would also recommend an if function around that switch to make sure 
> that the POST var has been sent in the first place
> 
> if (isset($_POST['usertype'])) {
>     switch ($_POST['usertype']) {
>         case "student":
>         case "staff":
>         case "admin":
>             break;
>         default:
>             // ...
>     }
> }

On that topic...

<tip type="Giving variables in PHP default values.">
Here's a terribly useful function I wrote ages ago when I started out
writing PHP. As those of you who hack in ColdFusion know, the CFPARAM
tag can be terribly useful for assigning default values to variables.
I needed something that did something like that in PHP, so I wrote
this:

<pre>
/**
  * Checks if $var is already defined and if not, sets it to $default.
  *
  * @param  $var         Variable to check.
  * @param  $default     Value to give the checked variable if found to
  *                      be null; "" by default.
  * @param  $catchNulls  TRUE: treat empty strings as null; FALSE by
  *                      default.
  *
  * @note   It's a lot like ColdFusion's <CFPARAM> tag.
  */
function SetDefault(&$var, $default="", $catchNulls=false)
{
     if (!isset($var) || ($catchNulls && $var == ""))
         $var = $default;
}
</pre>

In the above code, if the default usertype was "student", then you'd do:

<pre>
SetDefault($_POST['usertype'], 'student');
</pre>

If $_POST['usertype'] has a value, nothing happens, but if it doesn't,
it gets the value 'student'.
</tip>

K.

-- 
Keith Gaughan, Developer
Digital Crew Ltd., Pembroke House, Pembroke Street, Cork, Ireland
http://digital-crew.com/


-- 
No virus found in this outgoing message.
Checked by AVG Anti-Virus.
Version: 7.0.300 / Virus Database: 265.6.9 - Release Date: 06/01/2005



More information about the thelist mailing list