Get and remove the first element of an array in PHP

Hi I am encoding a system in which I need a function to get and remove the first element of an array. This array has numbers ie

0,1,2,3,4,5

how can I go through this array and each pass will get a value and then remove it from the array, so at the end of 5 rounds the array will be empty.

Thanks in advance

+6
source share
2 answers

You can try using foreach / unset rather than array_shift.

$array = array(0, 1, 2, 3, 4, 5); foreach($array as $value) { // with each pass get the value // use method to doSomethingWithValue($value); echo $value; // and then remove that from the array unset($array[$value]); } //so at the end of 6 rounds the array will be empty assert('empty($array) /* Array must be empty. */'); ?> 
+6
source

You can use array_shift to do this:

 while (($num = array_shift($arr)) !== NULL) { // use $num } 
+18
source

Source: https://habr.com/ru/post/919917/


All Articles