Ashlar
Ashlar

Reputation: 676

How do I reset an array to empty in PHP?

Looking through the available functions in the API, I cannot find one that will start an array from empty again.

Upvotes: 4

Views: 19646

Answers (7)

Sandro Rosa
Sandro Rosa

Reputation: 517

Suppose anyway that we have a loop where we shall fill an array -- for example of errors tracked per each record in a table. I have been thought to not instantiate a new variable per each step, but to use a set of declarations before the loop starts. Hence, I feel the above solution given by PHIHAG, namely

array_splice( $ar, 0, count( $ar ) );

as the best in any case. It is not recommended to continuous fill $ar through

$ar[] = [ <an-array-of-errors-strings-per-each-record> ];

because it could tend to explode if the number of output records would be very very large. Hence fill-and-empty looks as the best performing strategy.

Upvotes: 0

drmad
drmad

Reputation: 630

Nowadays (actually, since 2012) we can use:

$array = [];

More elegant and consistent with other languages.

Upvotes: 5

phpmeh
phpmeh

Reputation: 1792

Also, don't use unset( $array ); The execution time is way longer than = array();

Upvotes: 0

Tarek
Tarek

Reputation: 3798

$myarray=array(); // Reset $myarray to an empty array.

Upvotes: 1

phihag
phihag

Reputation: 288100

In most cases, just assign a new array:

$ar = array();

If you really want to modify the array in-place, use array_splice:

array_splice($ar, 0, count($ar));

Upvotes: 5

Polynomial
Polynomial

Reputation: 28316

You just set your variable to a new blank array.

$array = array();

Upvotes: 3

Gigi
Gigi

Reputation: 29461

If I remember correctly:

$myarray = array();

Upvotes: 15

Related Questions