views:

71

answers:

4

Under what circumstances would

$array[$index] = $element;

and

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

be different?

Assuming I am not using any references in my array, are these logically equivalent?

+3  A: 
unset($array[$index]);

would raise an E_NOTICE if $index is not found within $array. Other than that it looks the same.

Fanis
A: 

if you need to know is exist there before assigning (isset) is useful use "unset", but these simply add a step to "unset".

for example:

if ($array[$index]=="a")
   unset($array[$index]);

...

if (!isset($array[$index]))
   $array[$index] = $element;
andres descalzo
+4  A: 

If $index isn't numeric second variant would always append element to the end of array, so the order of keys will be changed.

Juicy Scripter
+3  A: 

The order is changed if you first remove a key and then add it again:

$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);

Output:

Array
(
    [foo1] => baz
    [foo2] => bar2
)

Array
(
    [foo2] => bar2
    [foo1] => baz
)
truppo