[php] How to Remove Array Element and Then Re-Index Array?

I have some troubles with an array. I have one array that I want to modify like below. I want to remove element (elements) of it by index and then re-index array. Is it possible?

$foo = array(

    'whatever', // [0]
    'foo', // [1]
    'bar' // [2]

);

$foo2 = array(

    'foo', // [0], before [1]
    'bar' // [1], before [2]

);

This question is related to php arrays indexing

The answer is


Unset($array[0]); 

Sort($array); 

I don't know why this is being downvoted, but if anyone has bothered to try it, you will notice that it works. Using sort on an array reassigns the keys of the the array. The only drawback is it sorts the values. Since the keys will obviously be reassigned, even with array_values, it does not matter is the values are being sorted or not.


array_splice($array, array_search(array_value, $array), 1);


In addition to xzyfer's answer

The function

function custom_unset(&$array=array(), $key=0) {
    if(isset($array[$key])){

        // remove item at index
        unset($array[$key]);

        // 'reindex' array
        $array = array_values($array);

        //alternatively
        //$array = array_merge($array); 

    }
    return $array;
}

Use

$my_array=array(
    0=>'test0', 
    1=>'test1', 
    2=>'test2'
);

custom_unset($my_array, 1);

Result

 array(2) {
    [0]=>
    string(5) "test0"
    [1]=>
    string(5) "test2"
  }

Try with:

$foo2 = array_slice($foo, 1);

2020 Benchmark in PHP 7.4

For these who are not satisfied with current answers, I did a little benchmark script, anyone can run from CLI.

We are going to compare two solutions:

unset() with array_values() VS array_splice().

<?php

echo 'php v' . phpversion() . "\n";

$itemsOne = [];
$itemsTwo = [];

// populate items array with 100k random strings
for ($i = 0; $i < 100000; $i++) {
    $itemsOne[] = $itemsTwo[] = sha1(uniqid(true));
}

$start = microtime(true);

for ($i = 0; $i < 10000; $i++) {
    unset($itemsOne[$i]);
    $itemsOne = array_values($itemsOne);
}

$end = microtime(true);

echo 'unset & array_values: ' . ($end - $start) . 's' . "\n";

$start = microtime(true);

for ($i = 0; $i < 10000; $i++) {
    array_splice($itemsTwo, $i, 1);
}

$end = microtime(true);

echo 'array_splice: ' . ($end - $start) . 's' . "\n"; 

As you can see the idea is simple:

  • Create two arrays both with the same 100k items (randomly generated strings)
  • Remove 10k first items from first array using unset() and array_values() to reindex
  • Remove 10k first items from second array using array_splice()
  • Measure time for both methods

Output of the script above on my Dell Latitude i7-6600U 2.60GHz x 4 and 15.5GiB RAM:

php v7.4.8
unset & array_values: 29.089932918549s
array_splice: 17.94264793396s

Verdict: array_splice is almost twice more performant than unset and array_values.

So: array_splice is the winner!


After some time I will just copy all array elements (excluding these unwanted) to new array


If you use array_merge, this will reindex the keys. The manual states:

Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

http://php.net/manual/en/function.array-merge.php

This is where i found the original answer.

http://board.phpbuilder.com/showthread.php?10299961-Reset-index-on-array-after-unset()


You better use array_shift(). That will return the first element of the array, remove it from the array and re-index the array. All in one efficient method.


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to indexing

numpy array TypeError: only integer scalar arrays can be converted to a scalar index How to print a specific row of a pandas DataFrame? What does 'index 0 is out of bounds for axis 0 with size 0' mean? How does String.Index work in Swift Pandas KeyError: value not in index Update row values where certain condition is met in pandas Pandas split DataFrame by column value Rebuild all indexes in a Database How are iloc and loc different? pandas loc vs. iloc vs. at vs. iat?