Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP unset vs array_pop?

Tags:

arrays

php

unset

If I want to remove the last element of an array, I can use either of these two code:

  1. array_pop($array); (the return value is not used)

  2. unset($array[count($array) -1]);

Is there any performance or semantic difference between them?

If not, which is preferred?

like image 577
Pacerier Avatar asked Jul 30 '13 12:07

Pacerier


2 Answers

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"
like image 178
BenLanc Avatar answered Sep 18 '22 21:09

BenLanc


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.

like image 28
Oswald Avatar answered Sep 21 '22 21:09

Oswald