How To Remove Empty Array Elements In PHP

PHP LogoQuick PHP tip: It is common to want to explode a string based on some delimiting character, then iterate over the array. Most of the time you don’t care about the empty items in the array. Suppose, for example, you have a dynamically constructed string of id numbers from a database or something and you want to iterate over them and do something. Here is a quick code sample to remove any entry that evaluates as false in the array.

Suppose you want to take a CSV string that might have some empty slots and clean it up.

Again, note that any array item that returns false will be removed. This includes 0, ” (empty strings), null, ‘false’, etc. The array_filter function can take a 2nd parameter for a callback function. This will let you do much more powerful decisioning on which items to remove from the array. Just have your callback return false for values you want to have removed.

3 thoughts on “How To Remove Empty Array Elements In PHP

  1. meathead says:

    Your examples above don’t work if you enter a space between or after any of the commas…

    • meathead says:

      For example, try:

      ‘1,2,3,,5,6,,8, ‘
      or
      ‘1,2,3, ,5,6,,8,’

      Can a simple trim fix this problem? I thought your solution would help me, but that’s exactly what I had already tried. Basically, if the user inputs a space as the last value, that value is exploded into its own empty array value. I thought the trim function would solve this problem, but evidently I’m doing it wrong…

      • Lee says:

        Keep in mind that you can provide your own callback function to handle more complex scenarios. Perhaps write a callback function that trims the values before evaluating them.

Leave a Reply

Your email address will not be published. Required fields are marked *