8

I have a loop that runs 47 times on my page. During the course of each loop, any error messages are entered into err[] and are printed out. I'm trying to blank the array after each iteration and I'm running into some trouble.

There could be 4 or 5 error messages per iteration, sometimes none. Is there an easier way of resetting the entire array after each iteration beyond running another foreach loop and unsetting each value? A way of clearing all contents and resetting the indexes without actually removing the array itself?

2
  • 1
    What's the problem with overwriting the current array with a new empty array? Do you keep references to the array? Commented Nov 1, 2011 at 19:27
  • "Is there an easier way of resetting the entire array after each iteration"- which code do you currently use for that? Commented Mar 21 at 12:28

3 Answers 3

14

You ought to use: unset ( $err );

Sign up to request clarification or add additional context in comments.

3 Comments

Hmm...that worked. I must've had something else wrong as I tried that previously and it didn't work. Seems to be doing the trick now. Thanks!
No problem. If you want you can accept this as the answer so others can find it easier. Your issue may have been including the braces. That sometimes catches me.
You're right. From his statement though I interpreted that he's initializing the array somewhere within the loop. Guess that was a large assumption on my part, but he seems to have it working.
10

Set it to array(), and you should be fine.

Comments

1
$clear = array();
foreach($your_array_variable as $key=>$val){
    $val = '';
    $clear [$key] = $val;
}
print_r($clear);

The below code is to unset same array,

foreach($your_array_variable as $key=>$val){
    $val = '';
    $your_array_variable[$key] = $val;
}
print_r($your_array_variable);

Both of the above code will help you to just unset the values only and won't clear the keys. So keys will be as it is but values will be cleared.

Where it's output will be like below,

array(
[0]=>
[1]=>
)

if you use $your_array_variable = array(); then you will be getting the below output,

Array(
)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.