7

Hi I am coding a system in which I need a function to get and remove the first element of the array. This array has numbers i.e.

0,1,2,3,4,5

how can I loop through this array and with each pass get the value and then remove that from the array so at the end of 5 rounds the array will be empty.

Thanks in advance

André Figueira
  • 6,048
  • 14
  • 48
  • 62
  • Take a look at [`array_shift`](http://www.php.net/manual/en/function.array-shift.php) – sachleen Jul 07 '12 at 02:26
  • Duplicate of http://stackoverflow.com/questions/369602/how-to-delete-an-element-from-an-array-in-php – Fluffeh Jul 07 '12 at 02:26
  • 1
    `array_shift` will do that, but do you really need to empty the array incrementally? – Jon Jul 07 '12 at 02:26
  • 1
    not a duplicate, i don't have the key to unset it, i am looping through. yes needs to be emptied incrementally. I looked at array_shift but couldn't tell weather it removes that array item after returning it... – André Figueira Jul 07 '12 at 02:33
  • As stated in the documentation @sachleen linked: "array_shift() shifts the first value of the array off and returns it, shortening the array by one element" – Chris Trahey Jul 07 '12 at 02:42
  • That's what I thought when i read it but i tried it but it didn't work... – André Figueira Jul 07 '12 at 02:44
  • Am trying a different approach, instead of interating with a while, going to use a foreach, no need to delete and use the first in the array. – André Figueira Jul 07 '12 at 03:00

2 Answers2

19

You can use array_shift for this:

while (($num = array_shift($arr)) !== NULL) {
  // use $num
}
6

You might try using foreach/unset, instead of 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. */');
?>
Jens A. Koch
  • 39,862
  • 13
  • 113
  • 141
  • This answer works by happenstance (keys and values are identical) and is misleading to readers. It is not a reliable approach to use `unset($array[$value])` in the wild. – mickmackusa May 19 '23 at 00:55