Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Move associative array element to beginning of array

Tags:

php

People also ask

How do you insert an item at the beginning of an array in PHP?

The array_unshift() function inserts new elements to an array. The new array values will be inserted in the beginning of the array. Tip: You can add one value, or as many as you like.

How do you get the first key of an associative array?

Starting from PHP 7.3, there is a new built in function called array_key_first() which will retrieve the first key from the given array without resetting the internal pointer. Check out the documentation for more info. You can use reset and key : reset($array); $first_key = key($array);

How do you push associative arrays?

Use the array_push() Method to Insert Items to an Associative Array in PHP.


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.


If you have numerical array keys and want to reindex array keys, it would be better to put it into array_merge like this:

$myArray = array_merge(array($key => $value) + $myArray );

A bit late, but in case anyone needs it, I created this little snippet.

function arr_push_pos($key, $value, $pos, $arr) 
{
    $new_arr = array();
    $i = 1;

    foreach ($arr as $arr_key => $arr_value) 
    {
        if($i == $pos) 
            $new_arr[$key] = $value;

        $new_arr[$arr_key] = $arr_value;

        ++$i;
    }

    return $new_arr;
}

Just adjust it to suit your needs, or use it and unset the index to move. Works with associative arrays too.


Here's another simple one-liner that gets this done using array_splice():

$myArray = array_splice($myArray,array_search('one',array_keys($myArray)),1) + $myArray;

if you have 2 arrays, 1st has elements to move to the top of 2nd array of elements, you can use

$result = \array_replace($ArrayToMoveToTop, $myArray);

Here is a code sample:

//source array    
$myArray = [
    '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',
];
// set necessary order
$orderArray = [
    'one' => '',
    'two' => '',
];
//apply it
$result = \array_replace($orderArray, $myArray);
\print_r($result);