We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 53390
    • 42 Posts
    Hi,
    is it normal that I couldn't use an array in a php snippet function? I spent half a day trying to figure out. The code was working outside modx if I place it on a separate test.php and access it directly through localhost but once it is imported to the chunk and template it doesn't work. Actually, I had problems only when I tried to assign or read values inside of a function but it was working in the main file code. I ried to access rhe array in both ways as 'global $myArray' and through $GLOBALS['myArray'] but no success.
    The question, is there any bug or banned global variables in modx? Did anybody experience this issue before? The code here is not authentic because I solved this by removing a function but was similar to this:
    $myArray = array();
    
    function test(){
      global $myArray; 
      $myArray[0] = 'value01'; 
    }
    
    test();
    
    // echo $myArray[0]; // not working in modx
    return $myArray[0]; // not working in modx
    
    

    This is working fine in a separate php file but not in ModX and does not generate any errors. Just outputs nothing array is empty.
    Any thoughts?

    This question has been answered by BobRay. See the first response.

      • 52064
      • 120 Posts
      Avoid using global. It's dangerous.
      Also in modx it always checks that the function has not already been instantiated.

      $myArray = array();
      if (!function_exists('test')) {
          function test($myArray){
            $myArray[0] = 'value01'; 
            return $myArray;
          }
      }
       
      $myArray=test($myArray);
      
        FerX - Developer at Eracom s.r.l.
      • discuss.answer
        • 3749
        • 24,544 Posts
        If you really want to modify the array inside the function and have the change persist outside the function, you can pass it by reference instead of using a global value.


        $myArray = array();
        
        function test(&$myArray){
          $myArray[0] = 'value01'; 
        }
         
        test($myArray);
         
        // echo $myArray[0]; // not working in modx
        return $myArray[0]; // not working in modx
        

          Did I help you? Buy me a beer
          Get my Book: MODX:The Official Guide
          MODX info for everyone: http://bobsguides.com/modx.html
          My MODX Extras
          Bob's Guides is now hosted at A2 MODX Hosting