OBAID
OBAID

Reputation: 1539

Change position of an associative array index in PHP

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 it builds when a function call on function return i am getting this array.

Upvotes: 1

Views: 974

Answers (3)

KIKO Software
KIKO Software

Reputation: 16688

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.

Upvotes: 3

Indrasis Datta
Indrasis Datta

Reputation: 8618

You need not make this too complicated or use any fancy functions. Just follow a few simple steps.

  • Store the errors sub array in another variable $errorField.
  • Unset the array index "errors"
  • Append this $errorField to a new key "errors".

    $errorField = $array['errors'];
    unset($array['errors']);
    $array['errors'] = $errorField;
    

Upvotes: 3

jeroen
jeroen

Reputation: 91744

Why does the order in the array matter?

If you really need that visually, you should initialize your array before you use it and overwrite the values when you fill it:

$arr = [
  'savedRows' => 0,
  'success' => '',
  'errors' => [],
]
// the rest of your code

Note that the order should not matter, if it does, you have another problem that you should fix.

Upvotes: 2

Related Questions