Thursday, 30 August 2018

Reversing an associative array with PHP key preservation

Following example of an array:
array(14) {
  ["label_text"]=> string(10) "Label text"
  ["e-mail"]=> string(6) "E-Mail"
  ["company"]=> string(7) "Company"
  ["last_name"]=> string(9) "Last name"
  ["first_name"]=> string(10) "First name"
}

What I want to do is just reverse the elements, so that the result is this:
array(14) {
  ["first_name"]=> string(10) "First name"
  ["last_name"]=> string(9) "Last name"
  ["company"]=> string(7) "Company"
  ["e-mail"]=> string(6) "E-Mail"
  ["label_text"]=> string(10) "Label text"
}

There must be a native php for this, but I think I'm blind. I just don't know which function to use.
Any help appreciated!

array array_reverse ( array $array [, bool $preserve_keys = false ] )
Takes an input array and returns a new array with the order of the elements reversed.
Note: make sure you read the documentation about the 2nd argument of said function.

0 comments:

Post a Comment