PHP Undefined variable in a closure

The following snippet returns a bunch of input fields but I’m unable to set their values because $data is undefined (it being inside a closure).

$row = array_map(function($n) {
    $name = sprintf('point[%0d]', $n+1);
    $value = $data['measurements'][$n];
    return form_input($name, $value, "class='input-mini'");
}, range($i*6, $i*6+5));

I know global variables are not cool. What’s the best way to get around this?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Inheriting variables from the parent scope

$row = array_map(function($n) use ($data) {
    $name = sprintf('point[%0d]', $n+1);
    $value = $data['measurements'][$n];
    return form_input($name, $value, "class='input-mini'");
}, range($i*6, $i*6+5));

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply