Swap array values with php

后端 未结 11 1056
感动是毒
感动是毒 2020-12-10 23:39

I have an array:

array(
    0 => \'contact\',
    1 => \'home\',
    2 => \'projects\'
);

and I need to swap the \'contact\' with

相关标签:
11条回答
  • 2020-12-11 00:38

    Try this:

    $a = array(
        0 => 'contact',
        1 => 'home',
        2 => 'projects'
    );
    $temp = $a[0];
    $a[0] = $a[1];
    $a[1] = $temp;
    
    0 讨论(0)
  • 2020-12-11 00:38

    I tested the 4 ways proposed to compare the performance:

    $array=range(0,9999); //First 10000 natural numbers
    $time=-microtime(true); //Start time
    for($i=0;$i<1000000;++$i){ //1 Millon swaps
        $a=array_rand($array); //Random position: ~60ms
        $b=array_rand($array); //Random position: ~60ms
        //Using a temp variable: ~70ms
        $temp=$array[$a];$array[$a]=$array[$b];$array[$b]=$temp;
        //Using list language construct: ~ 140ms
        list($array[$a],$array[$b])=array($array[$b],$array[$a]);
        //Using PHP 7.1+ syntax: ~ 140ms
        [$array[$a],$array[$b]]=[$array[$b],$array[$a]];
        //Using array_replace function: ~ 28000ms
        array_replace($array,[$array[$a],$array[$b]]);
    }
    $time+=microtime(true); //Elapsed time
    echo "Time: ",sprintf('%f', $time)," seconds";
    

    Although it is probably not the most comfortable way, using a temporary variable seems to be 2x faster than the next 2 methods, and 400x faster than using the array_replace function.

    0 讨论(0)
  • 2020-12-11 00:39

    New answer: (as others have expressed)

    I was not aware of Symmetric Array Destructuring at the time of posting, but that is a functionless, one-liner swapping technique -- I'd use that all day long.

    A relevant blog post/tutorial. An example implemention for bubble sorting.

    Code: (Demo)

    $a = ['contact', 'home', 'projects'];
    
    [$a[0], $a[1]] = [$a[1], $a[0]];
    
    var_export($a);
    

    Old answer:

    If you want to avoid using temporary data storage, or love a one-liner use array_replace().

    array_replace() will make adjustments in accordance with the indices:

    Code: (Demo)

    $a = array(
        0 => 'contact',
        1 => 'home',
        2 => 'projects'
    );
    
    var_export(array_replace($a,[$a[1],$a[0]]));
    

    Output:

    array (
      0 => 'home',
      1 => 'contact',
      2 => 'projects',
    )
    
    0 讨论(0)
  • 2020-12-11 00:40

    Solution:

    $a = array(
        0 => 'contact',
        1 => 'home',
        2 => 'projects'
    );
    

    list($a[0], $a[1]) = [$a[1], $a[0]];

    I have made function for it

    function swap(&$a, &$b){
        list($a, $b) = [$b, $a];
    }
    

    Usage:

    swap($a[0], $a[1]);

    0 讨论(0)
  • 2020-12-11 00:44
    $array = array(
        0 => 'home',
        1 => 'contact',
        2 => 'projects'
    );
    
    $t = $array[0];
    $array[0] = $array[1];
    $array[1] = $t;
    

    would be a simple enough approach…

    0 讨论(0)
提交回复
热议问题