Page 1 of 1

Favorite way of checking whether or not a variable exists...

Posted: Sun Mar 20, 2005 6:19 pm
by Ambush Commander
Favorite way of checking whether or not a variable exists... and then if it does, assign it to another variable (often with a default value), all without throwing an undefined index/variable error.

I used to do it like this:

Code: Select all

$var = 'Default Value';
if (!empty($variable)) {
  $var = $variable;
}
But when you have to do that with a lot of values, it's really awful.

Then I found out about PHP's laziness with ORs. So now I do this:

Code: Select all

$var = 'Default Value';
empty($variable) OR
  $var = $variable;
Hah! Works and throws no error! And is a bit easier to track. And then I realized that I could throw full conditionals capitilizing on PHPs laziness!

Code: Select all

!(!empty($authinfo['author'][1]) OR
  !trigger_error($this->base." must have a full name, please check database for errors", ERROR)  ) OR
  $this->fullname = $authinfo['author'][1];
But that's just conceptually WRONG. I'm using that code anyway though.

What's your favorite way of assigning variables while checking whether or not they exist?

Posted: Sun Mar 20, 2005 6:29 pm
by feyd

Code: Select all

$var = (isset($_POST['foo']) ? $_POST['foo'] : 'default');

// or the function way..

function isVar($keyname, $vararray, $default = '')
{
  return ($vararray[$keyname] ? $vararray[$keyname] : $default);
}

function postVar($key, $default = '')
{
  return isVar($key, $_POST, $default);
}

function getVar($key, $default = '')
{
  return isVar($key, $_GET, $default)
}

$var = postVar('foo');

Posted: Sun Mar 20, 2005 6:33 pm
by Ambush Commander
The functions cause problems when the arrays you're referencing don't exist.

Hmph... actually, I dabbled in that a bit. It's quite a bit of a hassle to write though, but I guess so is my code. Is that, like, better than what I'm doing? Or is there no fundamental difference?

Posted: Sun Mar 20, 2005 6:37 pm
by feyd
it's a quick-and-dirty versus maintain-and-migrate dilemma.

Posted: Sun Mar 20, 2005 6:38 pm
by Ambush Commander
Aha! I'll switch it over right away.

Posted: Sun Mar 20, 2005 6:54 pm
by Ambush Commander
By the way, Classes allow you to set default values. Is it recommended to use those values, like this:

Code: Select all

class bang
{
  
  var $bang = '';
  
  function setbang() {
    $this->bang = isset($_GET['bang']) ? $_GET['bang'] : $this->bang;
  }
  
}
or to do it like this:

Code: Select all

class bang
{
  
  var $bang;
  
  function setbang() {
    $this->bang = isset($_GET['bang']) ? $_GET['bang'] : '';
  }
  
}