【php】phpでcoalesce
問題
phpで、渡された値の中で、最初のnull(相当)でない値を返してください。
SQLにある COALESCE関数みたいなの。
答え
function coalesce() {
$args = func_get_args();
foreach ($args as $arg) {
if (!empty($arg)) {
return $arg;
}
}
return NULL;
}
用途に応じて、empty() は !== null などに書き換えてもよい。
使用例
echo coalesce(null, null, 1, 2, 3); // 1 echo coalesce(0, null, 1, 2, 3); // 1 echo html::coalesce(0, array(), 1, 2, 3); // 1