Home php How to remove empty elements in an array along with keys?

How to remove empty elements in an array along with keys?

Author

Date

Category

unset only removes the value, and I want to remove the keys as well.
What to use for this?


Answer 1, authority 100%

1)

$ new_array = array_filter ($ old_array, function ($ element) {
  return! empty ($ element);
});

2)

$ new_array = array_diff ($ old_array, array (''));

Answer 2, authority 17%

I went to look at the solution to a rather pressing problem. With a cursory glance, I looked around the topic and saw that there was no normal solution yet. I wrote the following:

foreach ($ old_array as $ element) {
        if (! empty ($ element)) {
          $ new_array [] = $ element;
        }
      }

Not elegant, but very simple and, most importantly, it works 🙂


Answer 3, authority 8%

Depending on what is considered an “empty” element, you can also suggest this option:

& lt;? php
$ arr = ['', 'a', 0, 2, 'd', false, 'p', '', null, 'c', 3,0];
var_dump ($ arr);
$ new_arr = array_diff ($ arr, array ('', NULL, false));
var_dump ($ new_arr);
// result
Array
(
  [0] = & gt;
  [1] = & gt; a
  [2] = & gt; 0
  [3] = & gt; 2
  [4] = & gt; d
  [5] = & gt;
  [6] = & gt; p
  [7] = & gt;
  [8] = & gt;
  [9] = & gt; c
  [10] = & gt; 3
  [11] = & gt; 0
)
Array
(
  [1] = & gt; a
  [2] = & gt; 0
  [3] = & gt; 2
  [4] = & gt; d
  [6] = & gt; p
  [9] = & gt; c
  [10] = & gt; 3
  [11] = & gt; 0
)

Answer 4, authority 8%

I would like to note that this code is not always enough:

$ new_array = array_diff ($ old_array, array (''));

For example, this is how we can run into trouble:

$ new_array = array_diff (explode ("/", "/ level1 / level2 /"), array ('' ));

At the output we will receive

Array
(
  [1] = & gt; level1
  [2] = & gt; level2
)

Although we really wanted to get it

Array
(
  [0] = & gt; level1
  [1] = & gt; level2
)

Therefore, for such cases, we use:

$ new_array = array_values ​​(array_diff (explode ("/", "/ level1 / level2 /"), array ( '')));

Answer 5

$ file =
      array_filter ($ file,
        function ($ element)
        {
          $ element = trim ($ element);
          if (strlen ($ element))
            return true;
        }
      );

Answer 6

Try it:

unset ($ arr [0]); sort ($ arr);

And that’s it, there are no empty keys.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions