PHP remove empty tring from array

Viewed 49

I'm trying to remove all empty strings "" from the kat-array. I tried to do it by using array_filter function like this:

$array = array_filter($array, "strlen");

The problem is that kat[4] is now an object instead of an array.

Any idea how I can remove empty stings from an array without transforming them into an object?

Before

enter image description here

After

enter image description here

2 Answers

Option 1:

$array = array_filter($array, "strlen");
var_dump(json_decode(json_encode($array), true));

Option 2:

   <?php
    $kat = [
    ["kat", "1"],
    ["kat", "1"],
    ["kat", "1", ""],
    ["", 'kat', "1.3"],
    
    ];
    
    var_dump(array_map('array_filter', $kat));

If filtering introduces key/index jumps/gaps, you can remedy by re-indexing your arrays with array_values() to avoid the objects when encoding the Php arrays to JSON.

If you have 0 indexed sequential keys in your Php arrays they become Javascript arrays when encoding to JSON.

<?php

$data = 
[ 
    [
        '', 'foo', 'bar'
    ],
    [
        'baz', 'bat'
    ]
];

$filtered =
    array_map(
        function($v) {
            return array_values(
                array_filter($v, 'strlen')
            );
        },
        $data
    );

var_export($filtered);
$json     = json_encode($filtered);
var_dump($json);

Output:

array (
  0 => 
  array (
    0 => 'foo',
    1 => 'bar',
  ),
  1 => 
  array (
    0 => 'baz',
    1 => 'bat',
  ),
)
string(29) "[["foo","bar"],["baz","bat"]]"
Related