arraySwap PHP function

I needed an easy way to swap two elements of a PHP array and came up with this function. It returns either the array with the two elements swapped or False if there’s a problem.

PHP:
  1. /**
  2. * Swaps two elements of an array
  3. *
  4. * This function will return the boolean <i>False</i> if $arr_source is not an array or if $arr_source[$key1] or $arr_source[$key2] do not exist.
  5. * @param mixed $arr_source The source array
  6. * @param mixed $key1 The key of one of the two elements to swap
  7. * @param mixed $key2 The key of the second of the two elements to swap
  8. * @return mixed Array with the two elements swapped
  9. */
  10. function arraySwap($arr_source, $key1, $key2)
  11.     {
  12.     if (!is_array($arr_source))
  13.         {
  14.         return false;
  15.         }
  16.     if (!isset($arr_source[$key1]) || !isset($arr_source[$key2]))
  17.         {
  18.         return false;
  19.         }
  20.    
  21.     $arr_tmp = $arr_source[$key1];
  22.     $arr_source[$key1] = $arr_source[$key2];
  23.     $arr_source[$key2] = $arr_tmp;
  24.    
  25.     return $arr_source;
  26.    
  27.     }

Question, Comments...

Do you have more questions. Please either leave a comment below or join us in our new forum.

Leave a Reply