Skip to content

Instantly share code, notes, and snippets.

@kafene
Created August 2, 2014 15:35
Show Gist options
  • Save kafene/d5abec1fbfa6be01ff1f to your computer and use it in GitHub Desktop.
Save kafene/d5abec1fbfa6be01ff1f to your computer and use it in GitHub Desktop.
PHP 5.6+ ifsetor/coalesce userspace implementation

Ref: https://wiki.php.net/rfc/ifsetor

So I found out something sad: the variadics RFC implementation was altered so that ...$arg can only come last.

And since we can't pass a non-variable default value by reference, it can go first, just kind of confusing looking, unfortunately.

<?php

function coalesce($default, &...$args) {
    return current(array_filter($args)) ?: $default;
}

$empty1 = [];
$empty2 = '';

$value1 = 'notempty';

echo coalesce('default', $empty1, $undefined, $empty2); // 'default'
echo coalesce('default', $empty1, $undefined, $value1, $empty2); // 'notempty'

You can try playing around with it on 3v4l.org.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment