Declaring a global array

后端 未结 3 1145
清酒与你
清酒与你 2021-01-03 23:09

Hi. I recently learned PHP and am trying to declare a global array so I can access inside a function. But I seem to be missing something because I get the error \'Undefined

3条回答
  •  时光说笑
    2021-01-03 23:58

    For anyone else hitting this old question in a google search,

    In the example the variable $second_array was declared a global, not the array created in the following line. To avoid this make sure the global declaration comes after the array declaration. My preference is to put global declaration in the function itself.

    $second_array = array();
    
    function operatii($v) {
    
        global $second_array;  
    
        $var1 = $second_array[count($second_array)-1];
        $var2 = $second_array[count($second_array)-2];
        $rez = null;
    
        echo $var1 . $var2 . "este?";
    }
    
    for ($i = 0; $i < count($a); $i++){
        if ($a[$i] === "+" || $a[$i] === "-" || $a[$i] === "*" || $a[$i] === "/" ) {
            operatii($a[$i]);
        } else {
            array_push($second_array, $a[$i]);
        }
    }
    

提交回复
热议问题