PHP: Swapping position of two array elements providing their keys

By Martin  on October 9th, 2008

I am working on a PHP thing where I need to be able to move array elements around based on their keys, the ordering is important. Non of the built in functions seem to do what I want and I could not find any similar problem/solution already posted somewhere so I made my own. In case someone needs the same thing, here it is, I place it in the public domain so feel free to use it as you want.

Looping through the array twice is not ideal but it was the quickest way to implement it not knowing all the nifty functions out there. It’s good enough for the moment, I rather not spend any more time on it now. If there is a more elegant solution let me know!


<?php
/**
* Swaps two elements in an array based on their keys.
* If one of the keys do not exist in the array the original array
* is returned.
* @param array $array The array to manipulate
* @param string $keyA The key to be swapped to the position of $keyB
* @param string $keyB The key to be swapped to the position of $keyA
* @author Martin Sveden, http://www.devcase.com
*/
function array_swap($array, $keyA, $keyB){
// To test this function:
// $arr = array('keyA' => array(1,2,3), 'keyB' => array(4,5,6),
// 'keyC' => 'hello');
// $arr = array_swap($arr, 'keyA', 'keyC');
// print_r($arr);

$i = 0;
$indexA = -1;
$indexB = -1;
foreach($array as $key => $val){
if($key == $keyA){
$indexA = $i;
}
if($key == $keyB){
$indexB = $i;
}
$i++;
}
$result = array();
if($indexA != -1 && $indexB != -1){
$x = 0;
foreach($array as $key => $val){
if($x == $indexA){
$result[$keyB] = $array[$keyB];
}
else if($x == $indexB){
$result[$keyA] = $array[$keyA];
}
else {
$result[$key] = $array[$key];
}
$x++;
}
}
else {
$result = $array;
}
return $result;
}
?>

In Dev | Tagged:

No comments yet.

Leave a reply


Comments links could be nofollow free.