Thursday, 3 May 2007

Sweeping off empty array values

While cleaning up an 'dirty' array, due to preparing another post, I recognized a solid way to remove all empty and unnecessary values from it.

So here's the short ride through the PHP array-wash plant.

<?php

$dirtyArray = array('', 1000, 1001, '', 1002, 1003, 'someValue', '');

/*Array
(
[0] =>
[1] => 1000
[2] => 1001
[3] =>
[4] => 1002
[5] => 1003
[6] => someValue
[7] =>
)*/

$sweepedArray = array_values(array_filter($dirtyArray));

/*Array
(
[0] => 1000
[1] => 1001
[2] => 1002
[3] => 1003
[4] => someValue
)*/
?>

7 comments:

Damien Seguy said...

In fact, the 'strlen' is not needed. You may simply call

$sweepedArray = array_filter($dirtyArray);

or with the array_values, if you want to get rid of the associated key in the process.

Raphael Stolt said...

Yeah you are right, works also this way. Looks like I scanned the PHP manual to fast.

Anonymous said...

Thank you man ;).

It works just PERFECT!

;)

quacos said...

Thanks, this made my day!

lordík said...

Awesome, works like a charm!

Anonymous said...

Really nice code :)

HB said...

Thanks for this, it's a simple and effective solution!