I need to use a variable variable for defining a lambda function inside of the callback of array_map()
. I get an "Undefined variable" WARNING for the variable that I am referencing. Subsequently, I do not get the expected result. The expected and actual results are commented within the code below. A PHP Sandbox of the problem is also given.
$a = "hello";
$$a = "world";
# Prints "world" as expected.
echo $hello;
# GIVES WARNING !!!! (Undefined variable $hello)
$res = array_map(fn($number) => $number . $$a, ["1", "2"]);
# Expected: ["1 world", "2 world"]
# Actual: ["1", "2"]
echo var_dump($res);
Tried:
Your issue is due to scoping rules. $$a
is not in the local scope of the function, while $world
is a regular variable that you've defined in the same scope as your array_map function, so it's recognized and can be used inside the function.
$a = "hello";
$$a = "world";
$world = $$a;
$res = array_map(fn($number) => $number . $world, ["1", "2"]);
var_dump($res);