PHP Undefined variable in closure

The following snippet returns a bunch of input fields, but I canโ€™t set their values โ€‹โ€‹because $ data is undefined (it is inside the 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 that global variables are not cool. What is the best way to get around this?

+8
php
source share
1 answer

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)); 
+20
source share

All Articles