Swap array values with php

后端 未结 11 1055
感动是毒
感动是毒 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:22

    If you don't want to use another variable:

        $array[0] = $array[0] + $array[1];
        $array[1] = $array[0] - $array[1];
        $array[0] = $array[0] - $array[1];
    
    0 讨论(0)
  • 2020-12-11 00:25
    $x = array('a', 'b', 'c', 'd');
    array_splice($x, 1, 2, array_reverse(array_slice($x, 1, 2)));
    var_dump($x);
    

    array_splice can replace a reversed array_slice

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

    In PHP 7.1+ syntax, you can use this

    [$Array[$a], $Array[$b]] = [$Array[$b], $Array[$a]];
    
    0 讨论(0)
  • 2020-12-11 00:34

    Just use a temp variable to hold it. So:

    $temp = $array[0];
    $array[0] = $array[1];
    $array[1] = $temp;
    

    That way you don't lose the value of one of them.

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

    I wrote simple function array_swap: swap two elements between positions swap_a & swap_b.

    function array_swap(&$array,$swap_a,$swap_b){
       list($array[$swap_a],$array[$swap_b]) = array($array[$swap_b],$array[$swap_a]);
    }
    

    For OP question (for example):

    $items = array(
      0 => 'contact',
      1 => 'home',
      2 => 'projects'
    );
    
    array_swap($items,0,1);
    var_dump($items);
    // OUTPUT
    
    array(3) {
       [0]=> string(4) "home"
       [1]=> string(7) "contact"
       [2]=> string(8) "projects"
     }
    

    Update Since PHP 7.1 it's possible to do it like:

    $items = [
      0 => 'contact',
      1 => 'home',
      2 => 'projects'
    ];
    
    [$items[0], $items[1]] = [$items[1], $items[0]];
    
    var_dump($items);
    // OUTPUT
    
    array(3) {
       [0]=> string(4) "home"
       [1]=> string(7) "contact"
       [2]=> string(8) "projects"
     }
    

    It's possible through Symmetric array destructuring.

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

    Just use a temp variable to hold one value as you swap the other. Then restore the first with the temp variable. For numbers there are other methods that don't require the use of temp variables but here it's the best (only?) way.

    $a = array(
        0 => 'contact',
        1 => 'home',
        2 => 'projects'
    );
    
    print_r($a);
    Array ( [0] => contact [1] => home [2] => projects )
    
    $tmp = $a[0];
    $a[0] = $a[1];
    $a[1] = $tmp;
    
    print_r($a);
    Array ( [0] => home [1] => contact [2] => projects )
    
    0 讨论(0)
提交回复
热议问题