0

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?

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

Comments

3
unset($array[$index]); 

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

Comments

3

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
)

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.