PHP – Swap Array Elements By Array Keys

The following PHP function could swap the array elements by the array keys.

function array_swap_assoc($key1, $key2, $array) {
  $newArray = array ();
  foreach ($array as $key => $value) {
    if ($key == $key1) {
      $newArray[$key2] = $array[$key2];
    } elseif ($key == $key2) {
      $newArray[$key1] = $array[$key1];
    } else {
      $newArray[$key] = $value;
    }
  }
  return $newArray;
}


 

try it out.

<?php
  $temp = array('a' => 'A', 'b' => 'B');
  $temp = array_swap_assoc('a', 'b', $temp);
  print_r($temp);

  // $temp => array('b' => 'B', 'a' => 'A');
?>

 

Done =)

Reference: Stack Overflow – Switch two items in associative array PHP

Advertisement

3 thoughts on “PHP – Swap Array Elements By Array Keys”

    1. Depends on what you want to end up with, in this example, it doesn’t change the key value pair but just swap their positions.

      Your comment will result in

      $temp => array('a' => 'B', 'b' => 'A');
      

      is that what u want to do?

      Like

  1. wtf? foreach?

    function array_swap_assoc($key1, $key2, $array) {
        if (isset($array[$key1], $array[$key2]))
        {
            $temp = $array[$key1];
            
            $array[$key1] = $array[$key2];
            $array[$key2] = $temp;
        }
        
        return $array;
    }
    

    Liked by 1 person

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.