Search code examples
phparraysunset

PHP unset vs array_pop?


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?


Solution

  • 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"