PHP table empty outside the function

advertisements

This question already has an answer here:

  • Reference: What is variable scope, which variables are accessible from where and what are “undefined variable” errors? 3 answers
<?php
echo '<pre>';
error_reporting(E_ALL);

$pid = '129';

$families = array
(
      "Griffin"=>array
                      (
                      "PTY"=>"Peter",
                      "STY"=>"X",
                      "QTY"=>"A|F"
                      ),
      "Quagmire"=>array
                      (
                      "NTY"=>"Glenn"
                      ),
      "Brown"=>array
                  (
                  "FTY"=>"Cleveland",
                  "OTY"=>"Q|G|T|Y",
                  "PTY"=>"Junior"
                  )
);

global $allid;

$allid = array();
function buildid($pid,$key,$val){

    if (preg_match("/\|/",$val)){
        $val = explode("|",$val);
            foreach($val as $val1){
                $id = $pid.'-'.$key.'-'.$val1;
                $allid[] = $id;

            }
    }
}

print_r($allid);  

foreach($families as $familieskey=>$familiesvalue){
    foreach($familiesvalue as $skey=>$sval){
        buildid($pid,$skey,$sval);
    }
}
echo '</pre>';
?>

Expected output for the above code:

Case1:

   Array
    (
        [0] => 129-QTY-A
        [1] => 129-QTY-F
    )
    Array
    (
        [0] => 129-OTY-Q
        [1] => 129-OTY-G
        [2] => 129-OTY-T
        [3] => 129-OTY-Y
    )

Case2:

 Array
    (
      [0] => 129-QTY-A
      [1] => 129-QTY-F
      [2] => 129-OTY-Q
      [3] => 129-OTY-G
      [4] => 129-OTY-T
      [5] => 129-OTY-Y
    )


The global $allid; goes into the function itself, not outside, i.e.

   function buildid($pid,$key,$val){
        global $allid;
        if (preg_match("/\|/",$val)){
    ...

The documentation points out that

Using global keyword outside a function is not an error. It can be used if the file is included from inside a function.

--> Unless you do include it from inside a function, it has no effect.

Edit to add: You also need to put the print_r after you run the code (i.e. right before echo '</pre>';) - currently, you are showing the content of the array right after you initialize it, then you fill it with data, and then your program ends.