Arthur Walker Arthur Walker - 1 year ago 71
MySQL Question

array_filter leaves one 0 and one null

I am using array_filter to filter out 0's and nulls' from an array.


while ($row1 = $sth1->fetch(PDO::FETCH_ASSOC)){

$rows_shared_id[$row1['shared_id']]['shared_id'] = $row1['shared_id'];


$erows_shared_id = array_filter($rows_shared_id);

foreach($erows_shared_id as $evalue){

echo $evalue['shared_id'] . "<br>";


The results, without array_filter, have multiple cells with a value of 0, or null. With array_filter, it filters out all 0's and nulls, except for the first of each. So, I am left with an array with one 0 and one null value. Why is it deleting all, but the first and how do I fix it? Thanks!

Answer Source

array_filter works on a single level array, but yours is a two-level array.

Try mapping array_filter to sub-arrays of your array:

$erows_shared_id = array_map('array_filter', $rows_shared_id);

You could then filter the array again to remove any keys that have empty arrays as children.

$erows_shared_id = array_filter(array_map('array_filter', $rows_shared_id));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download