Always Unset Values Passed by Reference in a Loop

I’d always read to unset the variables passed by reference in PHP’s foreach loop. Here’s an example:

    foreach ($posts as &$post) {
        $current_post = self::get_current_version_for_post($post->ID, true, true);
        $post->current_post_modified = mysql2date('U', $current_post->post_modified);


In the above code I was looping through a set of parent posts and using a custom method to get what I was calling the ‘current version’ which was really just the most recent child post. Then I added post modified date to the object.

Originally, I had forgotten to add the unset($post) line.
Later on however I was sorting the newly altered $posts objects by the current_post_modified value with this line and method:

    usort($posts, array('Essays_For_Comment', 'sort_by_date'));

    public function sort_by_date($a, $b) {
        $a = $a->current_post_modified;
        $b = $b->current_post_modified;
        if ($a == $b) {
            return 0;

        return ($a < $b) ? 1 : -1;

Each $a and $b was a post object passed with all it’s values. For some reason the last value of $a->current_post_modified; passed would equal the first objects value only, no other elements at all. It was because I had forgotten to unset the $post variable. That left a reference attached to the last element that was altered in the foreach() loop. (? is that what happened?).

This bug was not happening on my local install where I was running 5.4 but it was happening on the server running 5.3. ?

Leave a Reply

Your email address will not be published. Required fields are marked *