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

Advertisements

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;
    }
    

    Like

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s