If I want to remove the last element of an array, I can use either of these two code:
array_pop($array);
(the return value is not used)
unset($array[count($array) -1]);
Is there any performance or semantic difference between them?
If not, which is preferred?
unset
is no good if you need to "do" anything with the removed value (unless you have previously assigned it to something elsewhere) as it does not return anything, whereas array_pop
will give you the thing that was the last item.
The unset
option you have provided may be marginally less performant since you are counting the length of the array and performing some math on it, but I expect the difference, if any, is negligible.
As others have said, the above is true if your array is numerical and contiguous, however if you array is not structured like this, stuff gets complicated
For example:
<?php
$pop = $unset = array(
1 => "a",
3 => "b",
0 => "c"
);
array_pop($pop);
// array looks like this:
// 1 => "a", 3 => "b"
$count = count($unset) - 1;
unset($count);
// array looks like this because there is no item with index "2"
// 1 => "a", 3 => "b", 0 => "c"
array_pop($array)
removes the last element of $array
.
unset($array[count($array) -1]);
removes the element at index count($array) -1
. This element is not neccesarily the last element of the array.
Consider $array = array(0 => 'foo', 2 => 'bar', 1 => 'baz')
. In this case , $array[1]
is the last element. The code
foreach (array(0 => "foo", 2 => "bar", 1 => "baz") as $key => $value)
echo "$key => $value\n";
prints
0 => foo 2 => bar 1 => baz
Moreover, an element at index count($array) -1
might not even exist. There can be gaps in the set of indices and integer indices can be mixed with string indices.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With