Favorite way of checking whether or not a variable exists...
Posted: Sun Mar 20, 2005 6:19 pm
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:
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:
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!
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?
I used to do it like this:
Code: Select all
$var = 'Default Value';
if (!empty($variable)) {
$var = $variable;
}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;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];What's your favorite way of assigning variables while checking whether or not they exist?