8

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

7
  • Take a look at array_shift Commented Jul 7, 2012 at 2:26
  • Duplicate of stackoverflow.com/questions/369602/… Commented Jul 7, 2012 at 2:26
  • 1
    array_shift will do that, but do you really need to empty the array incrementally? Commented Jul 7, 2012 at 2: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... Commented Jul 7, 2012 at 2: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" Commented Jul 7, 2012 at 2:42

2 Answers 2

20

You can use array_shift for this:

while (($num = array_shift($arr)) !== NULL) {
  // use $num
}
Sign up to request clarification or add additional context in comments.

Comments

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. */');
?>

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.