Laravel Collections Using Get to lookup value or return default


Example

You often find yourself in a situation where you need to find a variables corresponding value, and collections got you covered.

In the example below we got three different locales in an array with a corresponding calling code assigned. We want to be able to provide a locale and in return get the associated calling code. The second parameter in get is a default parameter if the first parameter is not found.

function lookupCallingCode($locale)
{
    return collect([
        'de_DE' => 49,
        'en_GB' => 44,
        'en_US' => 1,
    ])->get($locale, 44);
}

In the above example we can do the following

lookupCallingCode('de_DE'); // Will return 49
lookupCallingCode('sv_SE'); // Will return 44

You may even pass a callback as the default value. The result of the callback will be returned if the specified key does not exist:

    return collect([
        'de_DE' => 49,
        'en_GB' => 44,
        'en_US' => 1,
    ])->get($locale, function() {
        return 44;
    });