Swap array values with php

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

提交回复
热议问题