Search code examples
phpjsonarray-differencearray-filter

Removed empty array element to json_encode after


I have simple array

$a = ['a', '', 'b','c','d'];

if i json_encode it i ll have

["a","","b","c","d"]

But if i ll try to remove empty value, with array_filter or array_diff

i ll have

{"0":"a","2":"b","3":"c","4":"d"}

but i dont need array keys to be encoded, i need an encoded array without empty elements and without array keys, how to solve?

Php sandbox example: http://sandbox.onlinephpfunctions.com/code/91635a5df7fcd954dd64fe92089f2beadc81c3c4


Solution

  • Try this:

    $a = array_values(array_filter($a));
    

    This resets the keys of your array to be sequential. Consider how the array keys work:

    $a = ['a', 'b'];       // [0 => 'a', 1 => 'b']
    unset($a[0]);          // [1 => 'b']
    $a = array_values($a); // [0 => 'b']