Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL ifnull equivalent for php

Tags:

php

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!

like image 969
Stop Slandering Monica Cellio Avatar asked Sep 09 '09 21:09

Stop Slandering Monica Cellio


People also ask

What is MySQL Ifnull?

MySQL IFNULL() Function The IFNULL() function returns a specified value if the expression is NULL. If the expression is NOT NULL, this function returns the expression.

How do I use Ifnull in MySQL?

The IFNULL function is a part of the MySQL control flow function used for handling NULL values. The IFNULL function accepts two expressions, and if the first expression is not null, it returns the first arguments. If the first expression is null, it returns the second argument.


2 Answers

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.

like image 26
André Hoffmann Avatar answered Oct 20 '22 19:10

André Hoffmann


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 functionality but without having to declare the function. In PHP versions 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);
like image 103
Dan Soap Avatar answered Oct 20 '22 19:10

Dan Soap