Is there a way of doing something like this:
$test_array = array(\"first_key\" => \"first_value\",
\"second_key\" => \"second_valu
A closure would work if you only need it once. I'd use a generator.
$test_array = [
"first_key" => "first_value",
"second_key" => "second_value",
];
$x_result = (function(array $arr) {
foreach ($arr as $key => $value) {
yield "$key loves $value";
}
})($test_array);
var_dump(iterator_to_array($x_result));
// array(2) {
// [0]=>
// string(27) "first_key loves first_value"
// [1]=>
// string(29) "second_key loves second_value"
// }
For something reusable:
function xmap(callable $cb, array $arr)
{
foreach ($arr as $key => $value) {
yield $cb($key, $value);
}
}
var_dump(iterator_to_array(
xmap(function($a, $b) { return "$a loves $b"; }, $test_array)
));