-2

The results in $data variable. I want to remove null values at output.

The following code:

    $data = json_decode(json_encode($data),true);

I am copying $data to $data1 later to merge the two variables using below code:

$data1 = $data;
$unique= array_merge($data1,$data);
$final =array_values(array_map("unserialize",array_unique(array_map("serialize", $unique))));
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • 2
    `$data ` being what exactly? If it's a collection then you can apply filters:`$data->filter(function ($element, $key) { return $element!==null; });` – ka_lin Jul 05 '17 at 08:16
  • actually, i am fetching data from database to $data array. – Prashanth vadla Jul 05 '17 at 08:18
  • Maybe you should rethink what you are doing: Encoding and then decoding, serializing and then unserializing, merging it with itself... Surely there is an easier way to get the results you need. – jeroen Jul 05 '17 at 08:20
  • This looks like an [X/Y problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) I suggest, instead of this question, ask a question about the problem you were trying to solve and came up with this solution. As it stands, this code is doing a lot of things that are a bit sub-optimal. – apokryfos Jul 07 '17 at 16:13
  • This question does not contain a [mcve] and is Unclear. – mickmackusa Sep 23 '22 at 08:05

3 Answers3

1

You can use array_filter to remove the null value fro the array

Do like this

$data = json_decode(json_encode($data),true);
$data =array_filter($data);

Modification
As you are dealing with Multi dimensional array (as you said in comment),to remove the array which have null data you need to use array_map , array_filter and in_array.

Do like this

$data = json_decode(json_encode($data),true);
$data =array_map('array_filter',$data);
$data=array_map(function ($data){
            if(!in_array(null,$data))
                return $data;
        },$data);
$data=array_filter($data);

It will give output as
enter image description here

It will work for you.

Bibhudatta Sahoo
  • 4,808
  • 2
  • 27
  • 51
0

array_filter will work perfectly if you're only working with arrays containing strings. Be careful otherwise as array_filter will also remove 0, '', and false.

See this answer: Remove empty array elements

Lasse
  • 77
  • 1
  • 10
0

If both $data adn $data1 are database results I can assume they are collections.

Then you can make 1 collection by applying union: $data->union($data1);

After which you can filter the result set:

$data->filter(function ($element, $key) { return $element!==null; });

ka_lin
  • 9,329
  • 6
  • 35
  • 56