phparrayssortingassociative-array

Change position of elements in an associative array


I have an associative array in PHP. I want to change position of an array index and its value.

Array
(
    [savedRows] => 1
    [errors] => Array
        (
            [0] => System has Skipped this row, because you have enter not valid value "" for field "description" in sheat "Electronics Laptops" row number "4"
    )

    [success] => successfully saved.
)

to like this

Array
(
   [savedRows] => 1
   [success] => successfully saved.
   [errors] => Array
        (
            [0] => System has Skipped this row, because you have enter not valid value "" for field "description" in sheat "Electronics Laptops" row number "4"
        )
)

I want to change ["errors"] index position from second to last and [success] index position at second when ever this array build.

This is a dynamic array not a static one; it builds when a function is call -- on return I am getting this array.


Solution

  • You can use array functions, but by far the easiest way to change it would be:

    $newRow = ['savedRows' => $oldRow['savedRows'],
               'success'   => $oldRow['success'], 
               'errors'    => $oldRow['errors']];
    

    But it is an associative array, not a numeric array, so order should not be that important.