Good morning!

I've spent hours on this to no avail. My understanding is that unset() only deletes the copy of the variable local to the current scope. But I am getting a very different result. I have the following structure and output. What am I doing wrong?

<?php
first_function();
second_function() {
   for ($count = 0; $count < $max; $count++) {
      $my_array = array[];   //initialize my array, local in this scope but can be called global in nested functions
      print_r($my_array );    //print 1: array should be always empty but is only in empty in FIRST loop.
      third_function();          //fills the array with numbers, see below, nested function declaring a global array
      print_r($my_array );    //print 3 of my_array, should be full of numbers from third_function global changes
      unset($my_array);      //delete my array so I can start with new array in next loop
      print_r($my_array );    //print 4 of my_array, should be unknown variable
      print('End one loop');
   }
}

third_function() {
   global $my_array;   //declare my global variable
   //...fill my now global array with stuff...
   print_r($my_array );  //print 2: should be filled with numbers. And it is.
}
?>

My output amazingly looks something like this

Array()
Array(45,48,38...all my numbers...)
Array()
ERROR: Notice -- Undefined variable: my_array
End one loop
Array(45,48,38...all my SAME numbers again as if array was NOT unset...)
......

The first and second print lines make sense. But shouldn't the third line be the array filled with numbers generated in third_function? The fourth line error makes sense as the variable is unset. But WHAT did I unset? The next time around in the loop, the array contains the SAME numbers from the previous loop and my new numbers simply get appended to the end of the ever growing array. Why?

This should not be that difficult but seems to be driving me crazy. Any help would be greatly appreciated.

alexander

    Hi alexander.

    That is strange PHP- no? Is this just pseudo-code - if so, why not post up the exact example? Or, even better, just those parts that exactly describe the problem you're attempting to solve?

    P.

      Hello Paul!

      Thank you for your help

      I simplified the code considerably to shorten the post. The main question being: if I create an array in a function and declare it global in various sub-functions (which does work as expected as the variables do update), shouldn't an unset delete the array in the initial function? And why, as seen in my output, does the array in the initial calling function appear to have no contents?

      I have a typo which should be: $my_array = array();

      The code seems to work fine on the first pass of the loop. It is only on the second pass where I found that $my_array is appending to the array contents in the first pass.

      In short, how do I declare an array in a function. Recognize it as global in sub-functions. (That part works already.) And then unset the global array in the declaring function? That is what I am ultimately trying to do. Empty and reuse a global array. Worked in C/C++...

      Thank you again for your help!
      alexander

        ExpertAlmost;10965234 wrote:

        I simplified the code considerably to shorten the post.

        Phew!

        OK, global variables are considered bad programming practice. Got to say it, although I do use them, albeit sparingly.

        I always declare any global variable as follows:

        $GLOBALS['myvar'] = 'blah';

        ... and always refer to them in the same way, inside and outside of functions, for example...

        $GLOBALS['myvar'] = array();
        
        foo();
        
        echo $GLOBALS['myvar'][0]; 
        
        
        function foo() {
            $GLOBALS['myvar'][0] = 'Hello, world!';;
        }
        
        

        The simplest way to remove all of the elements of a pre-declared array is to just re-assign it with an empty array (as you suggested), ie.

        $GLOBALS['myvar'] = array();

        Does that answer your question?

          About 20 years ago it occurred to me that software engineering was the Science of Successful Disappointments!
          That short bright feeling of success followed by the darkening sky of yet another bug...
          Right now I am enjoying that success brought about by your help!

          The one star that seems constant however is the communal kindness of fellow coders. Thank you all for sharing your ever precious time, hard-won expertise, and clever ideas. Should any of you ever find yourself in Thailand, let me know. Coffee and dessert are on me 🙂

          Apparently it is possible to create globals within functions. To complete the thread, I opted for the following (pseudo-code) solution which does work in my code:

          <?php
          first_function();
          second_function() {
          for ($count = 0; $count < $max; $count++) {
          global $my_array; // make the variable global here
          $my_array = array(); // set the variable to an array
          third_function();
          unset($my_array); // unset the variable here
          }
          }

          third_function() {
          global $my_array; // declare the variable as global here
          //...fill my global array with stuff...
          }
          ?>

          While I agree with the view that using globals is a dangerous thing, I have three arrays which are used almost everywhere and changed in many places. Hence the globals. Fortunately I am a strong code documenter (from years of repeated experience with "what in the world was I thinking when I wrote this?") so array changes are clearly and explicitly stated.

          Thank you again everyone! May your coding skies be bright and clear and path behind you littered with the desiccating corpses of vanquished bugs.
          alexander

            Write a Reply...