0
$crawler = new Crawler($xml);

$parkList = []; 

$crawler->filter('wfs|FeatureCollection > gml|featureMember > bm|ST_PARK_P > bm|NOM')->each(function (Crawler $actualPark, $i) {
        $parkList[$i] = [];
        $parkList[$i][] = $actualPark->text();
        //var_dump($parkList); // $parklist variable is filled
});

$crawler->filter('wfs|FeatureCollection > gml|featureMember > bm|ST_PARK_P > bm|geometry > gml|Point > gml|pos')->each(function (Crawler $actualPark, $i) {
        $parkList[$i][] = explode(' ', $actualPark->text())[0];
});
$crawler->filter('wfs|FeatureCollection > gml|featureMember > bm|ST_PARK_P > bm|geometry > gml|Point > gml|pos')->each(function (Crawler $actualPark, $i) {
        $parkList[$i][] = explode(' ', $actualPark->text())[1];
});


return $parkList; //parklist variable is strangely empty

Why my parkList variable is empty outside the .each function whereas I declared it outside the loop and fill its value during the loop... and the loop is successfully executed ?

Dispenam
  • 1
  • 1

1 Answers1

0

You're adding it to a local variable $parkList, not your global variable. Here is an demo for the different variable behaviour.

$list = [];

$localVariable = function() {
    $list[] = 'one';
};
$globalVariable = function()  {
    $GLOBALS['list'][] = 'two';
};
$defineLocalVariableAsGlobal = function() {
    global $list;
    $list[] = 'three';
};
$useListAsReference = function() use (&$list) {
    $list[] = 'four';
};

$localVariable();
$globalVariable();
$defineLocalVariableAsGlobal();
$useListAsReference();

var_dump($list); 

Output:

array(3) {
  [0]=>
  string(3) "two"
  [1]=>
  string(5) "three"
  [2]=>
  string(4) "four"
}

I would suggest providing the variable with use. This work even with nested calls. The other two ways only work for a global variable.

Because it is an array you need to provide it as an reference to be able to modify it. This would not be the case for objects.

ThW
  • 19,120
  • 3
  • 22
  • 44