0

condition in array_map is true, has inserted data and print statement inside condition. But why it doesn't return variable value. Here sucesss is printing, but $var variable's value is not updating. Array map returns array only, does it relate here ?

$var = 'fail';

array_map(function ($en, $np, $idSrvcs) {
    $data=[Fnct::filter_int($idSrvcs),Fnct::filter_str($en),Fnct::filter_str($np)];
    if(MdlDb::insrtData('srvcs_dtl',$data,'')){
        echo 'success'; // this line is printing
        $var = 'success';
    }
}, $en, $np, $idSrvcs);

echo $var // here output is fail.
Dipak
  • 931
  • 14
  • 33

1 Answers1

0

Because the variable $var in the anonymous function (the callback for array_map) has its own scope and it is a different variable. You can check by dumping $var before assigning value to it. It will be undefined, not 'fail'.

You can pass variables from parent scope inside the function with use keyword, like this:

// Inherit $message
$example = function () use ($message) {
    var_dump($message);
};
$example();

From https://www.php.net/manual/en/functions.anonymous.php Example #3 Inheriting variables from the parent scope.

Take note that just passing the variable wont be enough to modify it because function retrieves the copy (object would be passed by reference):

$s = 1;

$a = function () {$s++;};
$a(); // PHP Notice:  Undefined variable: b
var_dump($s); // 1

$b = function () use ($s) {$s++;};
$b();
var_dump($s); // 1

$c = function () use (&$s) {$s++;};
$c();
var_dump($s); // 2
blahy
  • 1,294
  • 1
  • 8
  • 9