PHP – Set Array Value from Closure Evaluation

There are times when you need to set a PHP array value from evaluated PHP code. Sometimes, you need to this using variables that won’t conflict with the current scope and with throwaway code that you won’t need again – so a closure is ideal.

Typically, you’ll need to assign the closure to a variable but this will negate the above requirement to not interfere with the current scope.

Here’s a way to do this:

return [
    'key1' => call_user_func( function() {
        $somevar = fn();
        // generate value
        return $calculated_value;
    }),
];

This has proved particularly used in Laravel configuration files.