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?
Fix Notice: Undefined Variable by using isset() Function This notice occurs when you use any variable in your PHP code, which is not set. Solutions: To fix this type of error, you can define the variable as global and use the isset() function to check if the variable is set or not.
Undefined variable: the variable's definition is not found in the project files, configured include paths, or among the PHP predefined variables. Variable might have not been defined: there are one or more paths to reach the line with the variable usage without defining it.
That means the PHP code tries to get the value of the field that no one has defined and thus does not exist. Quite expectedly, it does not work and raises a notice called Undefined Index in PHP.
A closure is an anonymous function that can access variables imported from the outside scope without using any global variables. Theoretically, a closure is a function with some arguments closed (e.g. fixed) by the environment when it is defined. Closures can work around variable scope restrictions in a clean way.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With