foreach与&引用的学习

在foreach中循环时

$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
unset($value);  // 最后取消掉引用 
var_dump($arr);  // $arr is now array(2, 4, 6, 8)
  • 此时输出$arr为array(2, 4, 6, 8);
$arr = array(1, 2, 3, 4);
foreach ($arr as $value) {
    $value = $value * 2;
}
unset($value);  // 最后取消掉引用 
var_dump($arr);  // $arr is now array(1, 2, 3, 4)
  • 此时输出$arr为array(1, 2, 3, 4);

进而衍生出不用额外的空间,对索引数组进行向前或向后移动一位的操作


class move
{
    public function before1(){
        $arr = array('a','b','c','d','e','f'); 
        foreach ($arr as $key => $value) {
            if($key == 0){
                $arr[(count($arr)-1)] = $value;
            }
            $value = &$arr[$key];
        }
        print_r($arr);
    }

    public function before2()
    {
        $arr = array('a','b','c','d','e','f');
        foreach ($arr as $key => $value) {
            if($key == 0){
                $arr[count($arr) -1] = $arr[0];
            }
            if($key-1>=0){
                $arr[$key-1] = $value;
            }
        }
        print_r($arr);
    }

    public function ahter1(){
        $arr = array('a','b','c','d','e','f');
        foreach ($arr as $key => $value) {
            if($key+1>=count($arr)){
                $arr[0] = $value;
            }else{
                $arr[$key+1] = $value;
            }
        }
        print_r($arr);
    }

    public function ahter2()
    {
        $arr = array('a','b','c','d','e','f');
        foreach ($arr as $key => $value) {
            if($key == 0){
                $arr[0] = $arr[count($arr) -1];
            }
            if($key+1$arr)){
                $arr[$key+1] = $value;
            }
        }
        print_r($arr);
    }

    public function ahter3()
    {
        $arr = array('a','b','c','d','e','f'); 
        foreach ($arr as $key => $value) {
            if($key == 0){
                $arr[1] = $arr['0'];
            }
            if($key + 2 < count($arr)){
                $value = &$arr[$key+2];
            }else{
                $value = &$arr[abs(count($arr)-$key-2)];
            }

        }
        print_r($arr);
    }
}

$res = new move;
$res->before1();
echo '
'
; $res->before2(); echo '
'
; $res->ahter1(); echo '
'
; $res->ahter2(); echo '
'
; $res->ahter3();

Array ( [0] => b [1] => c [2] => d [3] => e [4] => f [5] => a )
Array ( [0] => b [1] => c [2] => d [3] => e [4] => f [5] => a )
Array ( [0] => f [1] => a [2] => b [3] => c [4] => d [5] => e )
Array ( [0] => f [1] => a [2] => b [3] => c [4] => d [5] => e )
Array ( [0] => f [1] => a [2] => b [3] => c [4] => d [5] => e )

你可能感兴趣的:(php)