Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9253025
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T11:06:39+00:00 2026-06-18T11:06:39+00:00

I have a couple of queries about modifying an array during a foreach() loop.

  • 0

I have a couple of queries about modifying an array during a foreach() loop. In the code below I loop through three arrays that contain closures/callbacks and invoke each one. I append a closure to the end of each array during iteration, however sometimes foreach() doesn’t seem to recognise that the array has changed size and so the appended closure doesn’t get called.

class Foo
{
    private $a1 = array();
    private $a2 = array();

    public function f()
    {
        echo '<pre style="font-size: 20px;">';
        echo 'PHP: ' . phpversion() . '<br><br>';

        $this->a1[] = function() { echo 'a1 '; };
        $this->a1[] = array($this, 'g');
        foreach ($this->a1 as &$v)
        {
            // The callback added in g() never gets called.
            call_user_func($v);
            //echo 'count(v) = ' . count($v) . ' ';
        }

        echo '<br>';

        // The same thing works fine with a for() loop.
        $this->a2[] = function() { echo 'a2 '; };
        $this->a2[] = array($this, 'h');
        for ($i = 0; $i < count($this->a2); ++$i)
            call_user_func($this->a2[$i]);

        echo '<br>';

        // It also works fine using a local array as long as it
        // starts off with more than one element.
        $a3[] = function() { echo 'a3 '; };
        //$a3[] = function() { echo 'a3 '; };
        $i = 0;
        foreach ($a3 as &$x)
        {
            call_user_func($x);
            if ($i++ > 1) // prevent infinite loop
                break;

            // Why does this get called only if $a3 originally starts
            // with more than one element?
            $a3[] = function() { echo 'callback '; };
        }

        echo '</pre>';
    }

    private function g()
    {
        echo 'g() ';
        $this->a1[] = function() { echo 'callback '; };
    }

    private function h()
    {
        echo 'h() ';
        $this->a2[] = function() { echo 'callback '; };
    }
}

$foo = new Foo;
$foo->f();

Output:

PHP: 5.3.14-1~dotdeb.0

a1 g() 
a2 h() callback 
a3

Expected output:

a1 g() callback
a2 h() callback 
a3 callback

Output for $a3 if I uncomment the second element before the loop:

a3 a3 callback
  1. Why doesn’t the first loop foreach ($this->a1 as &$v) realise $v has another element to iterate over?
  2. Why does modifying $a3 work during the third loop foreach ($a3 as &$x), but only when the array starts off with more than one element?

I realise modifying an array during iteration is probably not a good idea, but since PHP seems to allow it I’m curious why the above works the way it does.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T11:06:40+00:00Added an answer on June 18, 2026 at 11:06 am

    1.Why doesn’t the first loop foreach ($this->a1 as &$v) realise $v has another element to iterate over?

    The behaviour looks to be due to the internal pointer being advanced on the array on each foreach iteration. Adding an array element to the end of the array on the last iteration of the array, that is when the internal pointer is already null, means that this element will not be iterated over. With some modifications to your code, this can be seen.

    class Foo
    {
        private $a1 = array();
        private $a2 = array();
    
        public function f()
        {
            echo '<pre style="font-size: 20px;">';
            echo 'PHP: ' . phpversion() . '<br><br>';
    
            $this->a1[] = function() { echo 'a1 <br/>'; };
            $this->a1[] = array($this, 'g');
            foreach ($this->a1 as $key => &$v)
            {
               //lets get the key that the internal pointer is pointing to 
               // before the call.
                      $intPtr = (key($this->a1) === null) ? 'null' : key($this->a1);
                    echo 'array ptr before key ', $key, ' func call is ',    
                           $intPtr, '<br/>' ;
                call_user_func($v);
                //echo 'count(v) = ' . count($v) . ' ';
            }
    
            echo '<br><br>';
    
            // The same thing works fine with a for() loop.
            $this->a2[] = function() { echo 'a2 '; };
            $this->a2[] = array($this, 'h');
            for ($i = 0; $i < count($this->a2); ++$i)
                call_user_func($this->a2[$i]);
    
            echo '<br><br>';
    
            // It also works fine using a local array as long as it
            // starts off with more than one element.
            $a3[] = function() { echo 'a3 '; };
            //$a3[] = function() { echo 'a3 '; };
            $i = 0;
            foreach ($a3 as &$x)
            {
                call_user_func($x);
                if ($i++ > 1) // prevent infinite loop
                    break;
    
                // Why does this get called only if $a3 originally starts
                // with more than one element?
                $a3[] = function() { echo 'callback '; };
            }
    
            echo '</pre>';
        }
    
        private function g()
        {
            echo 'g() <br>';
            $this->a1[] = function() { echo 'callback '; };
        }
    
        private function h()
        {
            echo 'h() <br>';
            $this->a2[] = function() { echo 'callback '; };
        }
    }
    
    $foo = new Foo;
    $foo->f(); 
    

    Output:

    array ptr before key 0 func call is 1
    a1 
    array ptr before key 1 func call is null <-will not iterate over any added elements!
    g() 
    
    a2 h() 
    callback 
    
    a3
    

    2.Why does modifying $a3 work during the third loop foreach ($a3 as &$x), but only when the array starts off with more than one element?

    Of course if you add an element to the array before the internal pointer returns null then the element will be iterated over. In your case if the array has one element then on the first iteration the internal pointer has already returned null. However, if there is initially more than one element then the additional element can be added on the first iteration as the internal pointer will be pointing to the second intial element at this time.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a couple of LINQ to SQL queries that I feel take a
I have couple of questions about AS3 variables handling by AVM/compiler/scope .1. This code
I have a couple stored procedures that run for about 2-3 minutes a piece
I have a server-side code written in Node.js that makes 6 SQL queries in
I have couple of dozen pieces of data that I need to save and
I have couple resource DLLs that I currently load when application starts using following
We have couple different web-apps that share the same db link. The hibernate layer
ok I have couple of .NET classes that I want to use in VBA.
I have a table that stores data about a large number of files, such
I have seen a couple of instances now where some legacy code I'm working

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.