International PHP Conference Munich 2025

Voting

: four plus two?
(Example: nine)

The Note You're Voting On

kokos at lac dot lviv dot ua
23 years ago
It may seem obvious from the above posts, but cost me a bit of
braindamage to figure this out...

Contrary to the equivalence noted on this page
$input[$x] = $y <==> array_splice ($input, $x, 1, $y)
array_splice() will not always work as expected,
even provided that you have only INTEGER keys!

The following code:
$t=array('a','b','c','d','e');
var_dump($t);

<?php
unset($t[0],$t[1],$t[3]);
$t[0]='f';
var_dump($t);

array_splice($t,0,1,'g');
var_dump($t);
?>

Will produce:
array(5) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
[3]=>
string(1) "d"
[4]=>
string(1) "e"
}
array(3) {
[2]=>
string(1) "c"
[4]=>
string(1) "e"
[0]=>
string(1) "f"
}
array(3) {
[0]=>
string(1) "g"
[1]=>
string(1) "e"
[2]=>
string(1) "f"
}

Note the position of $t[0] in the second call to var_dump().
And of course, array_splice() left it intact, changing $t[2] instead.
This is because it operates the _offset_, not the _index_. :)
I think that "equivalence note" should be considered buggy. ;)))

Best wishes.
KoKos.

<< Back to user notes page

To Top