tags:

views:

349

answers:

2

My scenario:

$exTime = get_cfg_var("session.gc_maxlifetime")?get_cfg_var("session.gc_maxlifetime"):1440;

I'd like it to be like mysql:

$exTime = isnull(get_cfg_var("session.gc_maxlifetime"),1440);

or something like it that would also test for FALSE ideally. That way I'd only have to call the function once!

I know I could just assign it to a var, but that would add another line to my code (oh nooes!!). It's really a cosmetic thing, I think it'd be easier to read. Anyway google hasn't helped me (inb4 someone proving me wrong). Thanks!

+1  A: 

How about adding this small function?

function isnull($var, $default=null) {
    return is_null($var) ? $default : $var;
}

I don't know of any function that does what you want, but since it's not that hard to implement you might as well do that if you use it a lot.

André Hoffmann
+2  A: 

As of PHP 5.3 you could also use the short ternary operator:

$exTime = get_cfg_var("session.gc_maxlifetime") ?: 1440;

This is basically your anticipated function but without having to declare the function. In PHP version prior to 5.3, you should go with André's answer.

Keep in mind though, that calling the function might throw warnings, if it is about to check arrays in which keys aren't specified:

$array = array(
    0 => array(
        0 => 100
    )
);

$example = isNull($array[0][1], 200);
Cassy
Won't this assign TRUE to $exTime if session.gc_maxlifetime is set? This doesn't really do it for me, because I need $exTime to hold the return value of get_cfg_var("session.gc_maxlifetime") *unless it's null/false*, not to hold TRUE or 1440. (I assume that that "isnull" is really "is_null" and you aren't using the function from andré). Thanks though, I didn't know about short ternary!
sequoia mcdowell
wait a second, just remove the "isnull" wrapper and that's the ticket! Thanks!http://www.asgrim.com/2009/06/30/awesome-short-ternary-operators/
sequoia mcdowell