Jump to content

[SOLVED] switching members in an array


php_joe

Recommended Posts

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

Link to comment
https://forums.phpfreaks.com/topic/71396-solved-switching-members-in-an-array/
Share on other sites

<?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>';
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.