Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removed empty array element to json_encode after [duplicate]

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

like image 356
MyMomSaysIamSpecial Avatar asked Mar 21 '26 22:03

MyMomSaysIamSpecial


2 Answers

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']
like image 162
cmbuckley Avatar answered Mar 23 '26 11:03

cmbuckley


This resets the array keys

$a = ['a', '', 'b', 'c', 'd'];
echo json_encode(array_values(array_filter($a)));
like image 29
Tobias Golbs Avatar answered Mar 23 '26 11:03

Tobias Golbs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!