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 8636955
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T10:21:28+00:00 2026-06-12T10:21:28+00:00

I have a very strange array sorting related problem in PHP that is driving

  • 0

I have a very strange array sorting related problem in PHP that is driving me completely crazy. I have googled for hours, and still NOTHING indicates that other people have this problem, or that this should happen to begin with, so a solution to this mystery would be GREATLY appreciated!

To describe the problem/question in as few words as possible: When sorting an array based on values inside a multiple levels deeply nested array, using a foreach loop, the resulting array sort order reverts as soon as execution leaves the loop, even though it works fine inside the loop. Why is this, and how do I work around it?

Here is sample code for my problem, which should hopefully be a little more clear than the sentence above:

$top_level_array = array('key_1' => array('sub_array' => array('sub_sub_array_1' => array(1),
                                                               'sub_sub_array_2' => array(3),
                                                               'sub_sub_array_3' => array(2)
                                                              )
                                         )
                        );

function mycmp($arr_1, $arr_2)
{
    if ($arr_1[0] == $arr_2[0])
    {
        return 0;
    }
    return ($arr_1[0] < $arr_2[0]) ? -1 : 1;
}

foreach($top_level_array as $current_top_level_member)
{
    //This loop will only have one iteration, but never mind that...
    print("Inside loop before sort operation:\n\n");
    print_r($current_top_level_member['sub_array']);

    uasort($current_top_level_member['sub_array'], 'mycmp');

    print("\nInside loop after sort operation:\n\n");
    print_r($current_top_level_member['sub_array']);
}
print("\nOutside of loop (i.e. after all sort operations finished):\n\n");
print_r($top_level_array);

The output of this is as follows:

Inside loop before sort operation:

Array
(
    [sub_sub_array_1] => Array
        (
            [0] => 1
        )

    [sub_sub_array_2] => Array
        (
            [0] => 3
        )

    [sub_sub_array_3] => Array
        (
            [0] => 2
        )

)

Inside loop after sort operation:

Array
(
    [sub_sub_array_1] => Array
        (
            [0] => 1
        )

    [sub_sub_array_3] => Array
        (
            [0] => 2
        )

    [sub_sub_array_2] => Array
        (
            [0] => 3
        )

)

Outside of loop (i.e. after all sort operations finished):

Array
(
    [key_1] => Array
        (
            [sub_array] => Array
                (
                    [sub_sub_array_1] => Array
                        (
                            [0] => 1
                        )

                    [sub_sub_array_2] => Array
                        (
                            [0] => 3
                        )

                    [sub_sub_array_3] => Array
                        (
                            [0] => 2
                        )

                )

        )

)

As you can see, the sort order is “wrong” (i.e. not ordered by the desired value in the innermost array) before the sort operation inside the loop (as expected), then is becomes “correct” after the sort operation inside the loop (as expected).

So far so good.

But THEN, once we’re outside the loop again, all of a sudden the order has reverted to its original state, as if the sort loop didn’t execute at all?!?

How come this happens, and how will I ever be able to sort this array in the desired way then?

I was under the impression that neither foreach loops nor the uasort() function operated on separate instances of the items in question (but rather on references, i.e. in place), but the result above seems to indicate otherwise? And if so, how will I ever be able to perform the desired sort operation?

(and WHY doesn’t anyone else than me on the entire internet seem to have this problem?)

PS.
Never mind the reason behind the design of the strange array to be sorted in this example, it is of course only a simplified PoC of a real problem in much more complex code.

  • 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-12T10:21:29+00:00Added an answer on June 12, 2026 at 10:21 am

    Your problem is a misunderstanding of how PHP provides your “value” in the foreach construct.

    foreach($top_level_array as $current_top_level_member)
    

    The variable $current_top_level_member is a copy of the value in the array, not a reference to inside the $top_level_array. Therefore all your work happens on the copy and is discarded after the loop completes. (Actually it is in the $current_top_level_member variable, but $top_level_array never sees the changes.)

    You want a reference instead:

    foreach($top_level_array as $key => $value)
    {
        $current_top_level_member =& $top_level_array[$key];
    

    EDIT:

    You can also use the foreach by reference notation (hat tip to air4x) to avoid the extra assignment. Note that if you are working with an array of Objects, they are already passed by reference.

    foreach($top_level_array as &$current_top_level_member)
    

    To answer you question as to why PHP defaults to a copy instead of a reference, it’s simply because of the rules of the language. Scalar values and arrays are assigned by value, unless the & prefix is used, and objects are always assigned by reference (as of PHP 5). And that is likely due to a general consensus that it’s generally better to work with copies of everything expect objects. BUT–it is not slow like you might expect. PHP uses a lazy copy called copy on write, where it is really a read-only reference. On the first write, the copy is made.

    PHP uses a lazy-copy mechanism (also called copy-on-write) that does
    not actually create a copy of a variable until it is modified.

    Source: http://www.thedeveloperday.com/php-lazy-copy/

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

Sidebar

Related Questions

I have a very strange problem with #any? printing true for an array that
Very simple situation... very strange problem. I have a retained iVar NSMutableArray that I
I have very strange problem while I am submitting a practice problem on codechef.
I have a very strange, very repeatable leak that doesn't appear to have anything
I have a very strange problem when I'm testing my application on device. I
I have a very strange problem. I have a working WCF service. [ServiceContract] public
I have a very strange problems in a PHP Soap implementation. 1) I have
A very strange thing, I have an array where element 7 is '[1000137d]' ,
I'm encountering a very strange problem using g++ 4.1.2. I have a very basic
I have a very strange problem while using my ListView. Only a part of

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.