27 April 2023

When working with associative arrays in PHP, there may be times when you need to reorder the elements of the array. For example, you may want to move a specific key and its value to the end of the array, so that it is the last element.

To accomplish this task, you can use the unset() and $array[$key] = $value functions. First, you need to determine the key that you want to move to the end of the array. Then, you can check if the key exists in the array using the array_key_exists() function. If the key exists, you can retrieve the corresponding value using $array[$key].

Next, you need to remove the key and its value from the array using the unset() function. This will delete the key and value from the array, without affecting any other elements.

Finally, you can add the key and value back to the array using $array[$key] = $value. This will add the key and value to the end of the array, so that it is the last element.

By using these simple functions, you can easily reorder the elements of a PHP associative array to meet your specific needs.

Source code viewer
  1. $key_name = 'my-key';
  2.  
  3. $item_clone = $array[$key_name];
  4. unset($array[$key_name]);
  5. $array[$key_name] = $item_clone;
Programming Language: PHP