1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Does foreach's array_expression get referenced in each loop?

Discussion in 'PHP' started by Ian08, Jan 29, 2019.

  1. #1
    Considering the following code:
    $ten_element_array = array(
        'one'   => '1',
        'two'   => '2',
        'three' => '3',
        'four'  => '4',
        'five'  => '5',
        'six'   => '6',
        'seven' => '7',
        'eight' => '8',
        'nine'  => '9',
        'ten'   => '10'
    );
    
    function some_func()
    {
        foreach ($GLOBALS['ten_element_array'] as $key => &$value)
        {
            if ($key == 'seven')
            {
                // do something
            }
            else
            {
                // do some other thing
            }
        }
        return implode(', ', $GLOBALS['ten_element_array']);
    }
    
    echo some_func();
    PHP:
    Does $ten_element_array get referenced 10 times in the foreach?
    SEMrush
     
    Solved! View solution.
    Last edited: Jan 29, 2019
    Ian08, Jan 29, 2019 IP
    SEMrush
  2. #2
    Yes, but what is with the globals?
     
    sarahk, Jan 29, 2019 IP
    Ian08 likes this.
  3. Ian08

    Ian08 Well-Known Member

    Messages:
    93
    Likes Received:
    4
    Best Answers:
    1
    Trophy Points:
    108
    #3
    Thank you very much.

    Do you mean why using $GLOBALS[' ... '] in the code? Because I think that's a prominent example of "referencing a variable". (Please correct me if I'm wrong.)

    The purpose of my question is to figure out the performance of using $GLOBALS[' ... '] as foreach's array_expression. According to your kind answer, $GLOBALS[' ... '] in that kind of situation does get referenced in the first loop and once again in every subsequent loop. And I think that's bad for performance. If $ten_element_array were $thousand_element_array instead, the $GLOBALS[' ... '] would then get referenced a thousand times in the foreach and that's even worse in my opinion.

    So I tested using the global keyword outside of the foreach against using $GLOBALS[' ... '] directly as foreach's array_expression. Such as:
    function some_func()
    {
        global $ten_element_array;
        foreach ($ten_element_array as $key => &$value)
        {
            if ($key == 'seven')
            {
                // do something
            }
            else
            {
                // do some other thing
            }
        }
        return implode(', ', $ten_element_array);
    }
    PHP:
    And the result shows that using the global keyword outside of the foreach is slightly faster, on average.
     
    Last edited: Jan 29, 2019
    Ian08, Jan 29, 2019 IP
  4. sarahk

    sarahk iTamer Staff

    Messages:
    25,265
    Likes Received:
    3,441
    Best Answers:
    100
    Trophy Points:
    665
    #4
    There are few times when a global variable is needed - sometimes you need a constant or there may be a config variable with named keys that can be referenced directly.

    Your example makes it seem that the global is updated in the foreach and that makes me extremely uncomfortable. I'm also not sure about your &$value - I thought that notation went out about a decade ago... or has it resurfaced?

    Can you give me a practical example of when a global array with thousands of rows would be used?
     
    sarahk, Jan 29, 2019 IP
  5. Ian08

    Ian08 Well-Known Member

    Messages:
    93
    Likes Received:
    4
    Best Answers:
    1
    Trophy Points:
    108
    #5
    Sorry, but I don't quite understand. In my example, the global variable surely is needed inside the function.

    Yeah. In my example, the values of the global variable are meant to be updated in the foreach, hence the &$value. More info at here. (Quote: "In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.")

    Would you mind explaining why that would make you extremely uncomfortable?

    Currently, I don't have a practical example. I was just describing the different situation in an exaggerative way in order to explain how the performance could become worse.
     
    Ian08, Jan 29, 2019 IP
  6. sarahk

    sarahk iTamer Staff

    Messages:
    25,265
    Likes Received:
    3,441
    Best Answers:
    100
    Trophy Points:
    665
    #6
    Any dataset that has 1000 rows would be best kept in a database and accessed as and when required. There could be multiple people accessing and updating the information so a fresh request from the database would be prudent - and calls to a database are quick and simple.

    
    function some_func($arr) {
       $output = [];
       foreach ($arr as $key => $value) {
         if ($key == 'seven') {
            // do something
         }
          else {
             // do some other thing
          }
          $output[$key] = $value;
       }
       return implode(', ', $output);
    }
    $list = get_values_from_database('xyz');
    $str = some_func($list);
    
    PHP:
     
    sarahk, Jan 29, 2019 IP
    Ian08 likes this.
  7. Ian08

    Ian08 Well-Known Member

    Messages:
    93
    Likes Received:
    4
    Best Answers:
    1
    Trophy Points:
    108
    #7
    Thanks for the tip. That's so true.
     
    Ian08, Jan 29, 2019 IP
  8. mmerlinn

    mmerlinn Notable Member

    Messages:
    2,261
    Likes Received:
    286
    Best Answers:
    6
    Trophy Points:
    290
    #8
    Why not test it and find out instead of coming here and waiting for a (hopefully) correct answer?
     
    mmerlinn, Feb 23, 2019 IP
  9. Ian08

    Ian08 Well-Known Member

    Messages:
    93
    Likes Received:
    4
    Best Answers:
    1
    Trophy Points:
    108
    #9
    Speed testing does not answer my question directly.
     
    Ian08, Feb 23, 2019 IP
  10. mmerlinn

    mmerlinn Notable Member

    Messages:
    2,261
    Likes Received:
    286
    Best Answers:
    6
    Trophy Points:
    290
    #10
    1) If you did it yourself you would not likely forget it in the future. Learning by doing embeds it deeper in your brain.
    2) I don't know what you mean by "speed testing" but a test should not have taken longer than a few minutes.
     
    mmerlinn, Feb 24, 2019 IP
  11. Ian08

    Ian08 Well-Known Member

    Messages:
    93
    Likes Received:
    4
    Best Answers:
    1
    Trophy Points:
    108
    #11
    I actually did a test. (see #3) But that was after I asked the question. Anyway, I will take your advice. Thanks.
     
    Ian08, Feb 24, 2019 IP