php_joe Posted October 1, 2007 Share Posted October 1, 2007 This may be a stupidly ignorant question, but is there a simple way of switching two members in an array without disturbing the rest of the array? For example: <? // Begin with: $array = array('one', 'two', 'three', 'four'); // End with: $newarray = array('one', 'three', 'two', 'four'); ?> I guess I could do something like this: <? // Begin with: $array = array('one', 'two', 'three', 'four'); foreach($array as $key => $value) { if($key == 1) $newarray[$key] = $array[$key+1]; else if($key == 2) $newarray[$key] = $array[$key-1]; else $newarray[$key] = $value; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/71396-solved-switching-members-in-an-array/ Share on other sites More sharing options...
Barand Posted October 1, 2007 Share Posted October 1, 2007 <?php $array = array('one', 'two', 'three', 'four'); function array_swap(&$arr, $n1, $n2) { $tmp = $arr[$n1]; $arr[$n1] = $arr[$n2]; $arr[$n2] = $tmp; } array_swap ($array, 1, 2); echo '<pre>', print_r($array, true), '</pre>'; ?> Quote Link to comment https://forums.phpfreaks.com/topic/71396-solved-switching-members-in-an-array/#findComment-359330 Share on other sites More sharing options...
php_joe Posted October 1, 2007 Author Share Posted October 1, 2007 Yes, that's better. Thank you. Quote Link to comment https://forums.phpfreaks.com/topic/71396-solved-switching-members-in-an-array/#findComment-359383 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.