Fix the Error: Filtering out Empty Arrays

Published by Helen Yu in

I am trying to filter out empty arrays from an array. In other words, I want to transform something that looks like this: ["a", "b", [], [], [1, 2, 3]] to look like ["a", "b", [1, 2, 3]]. My code looks like this:

function removeEmptyArrays($arr) {
  return array_filter($arr, "no_empty");
}

function no_empty($v) {
  if (count($v) == 0) {
    return FALSE;
  } else {
    return TRUE;
  }
}

However, somehow, the keys are messed up. Fix this incorrect code so that all tests pass.

Examples

// What I want:
removeEmptyArrays([1, 2, [], 4]) ➞ [0 => 1, 1 => 2, 2 => 4]

// What I am getting (skipped key 2!)
removeEmptyArrays([1, 2, [], 4]) ➞ [0 => 1, 1 => 2, 3 => 4]

Notes

N/A

Watch a quick demo on how Edabit works.