phparrayssortingassociative-array

PHP: Move associative array element to beginning of array


What would be the best method of moving any element of an associative array to the beginning of the array?

For example, say I have the following array:

$myArray = array(
    'two'   => 'Blah Blah Blah 2',
    'three' => 'Blah Blah Blah 3',
    'one'   => 'Blah Blah Blah 1',
    'four'  => 'Blah Blah Blah 4',
    'five'  => 'Blah Blah Blah 5',
);

What i want to do is move the 'one' element to the beginning and end up with the following array:

$myArray = array(
    'one'   => 'Blah Blah Blah 1',
    'two'   => 'Blah Blah Blah 2',
    'three' => 'Blah Blah Blah 3',
    'four'  => 'Blah Blah Blah 4',
    'five'  => 'Blah Blah Blah 5',
);

Solution

  • You can use the array union operator (+) to join the original array to a new associative array using the known key (one).

    $myArray = array('one' => $myArray['one']) + $myArray;
    // or      ['one' => $myArray['one']] + $myArray;
    

    Array keys are unique, so it would be impossible for it to exist in two locations.

    See further at the doc on Array Operators:

    The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.