代码之家  ›  专栏  ›  技术社区  ›  Steven Oxley

为什么在数组中设置一个元素和在数组中取消设置一个元素会有所不同?PHP

  •  0
  • Steven Oxley  · 技术社区  · 17 年前

    在什么情况下你会这样做

    $array[$index] = $element;
    

    unset($array[$index]);
    $array[$index] = $element;
    

    会有所不同吗?

    假设我没有在数组中使用任何引用,那么这些引用在逻辑上是等价的吗?

    4 回复  |  直到 17 年前
        1
  •  4
  •   Juicy Scripter    17 年前

        2
  •  3
  •   Fanis Hatzidakis    17 年前
    unset($array[$index]); 
    

        3
  •  3
  •   mthurlin    17 年前

    如果先删除密钥,然后再次添加,则会更改顺序:

    $arr = array("foo1" => "bar1", "foo2" => "bar2");
    $arr["foo1"] = "baz";
    print_r($arr);
    
    
    $arr = array("foo1" => "bar1", "foo2" => "bar2");
    unset($arr["foo1"]);
    $arr["foo1"] = "baz";
    print_r($arr);
    

    输出:

    Array
    (
        [foo1] => baz
        [foo2] => bar2
    )
    
    Array
    (
        [foo2] => bar2
        [foo1] => baz
    )
    
        4
  •  0
  •   andres descalzo    17 年前

    例如:

    if ($array[$index]=="a")
       unset($array[$index]);
    
    ...
    
    if (!isset($array[$index]))
       $array[$index] = $element;
    
    推荐文章