简体   繁体   中英

delete array value and then compact

I want to delete a value of a numbered index's array, and then compact the array so the left index is not empty. This is my code but i'd like to know if there is an array method which do that

for ($j = 30; $j < count($a); $j++) {
    if ($j+1 < count($a)) {
        $a[$j] = $a[$j+1];
    }
}
array_pop($a);

So this code remove the value of index 30 of the array and compact the array. I could use unset(a[30]) but that left me with an array with no index 30. And I can't iterate correctly that array.

You can iterate the array using foreach however to answer the index question:

unset($a[30]);
$a = array_values($a);

You might also use:

array_splice($a, 30, 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM