Home > Net >  Remove empty entries in associated array php
Remove empty entries in associated array php

Time:09-02

I have tried all the solutions suggested in this post but have not been able to make them work in my case.

My array :

array(2) {
  ["number_s"]=>
  array(14) {
    [0]=>
    string(2) "22"
    [1]=>
    string(2) "23"
    [2]=>
    string(0) ""
    [3]=>
    string(0) ""
    [4]=>
    string(0) ""
  }
  ["player_name"]=>
  array(14) {
    [0]=>
    string(9) "John Doe"
    [1]=>
    string(11) "Jack Sparrow"
    [2]=>
    string(0) ""
    [3]=>
    string(0) ""
    [4]=>
    string(0) ""
  }
}

I would like to remove all the empty entries but how to do that ?

Thanks a lot for help

CodePudding user response:

It seems like array_filter for each subarray will do what you want.

$array['number_s'] = array_filter($array['number_s']);
$array['player_name'] = array_filter($array['player_name']);

When called without callback function it just removes all empty entries. See docs for details.

But be aware that it will remove "0" and all values which considered empty.

CodePudding user response:

Assuming there aren't arbitrary numbers of subarrays, you may transverse them (as references) and use unset to remove them from the array:

foreach ($array as &$subarray) {
  foreach ($subarray as $key => $value) {
    if (empty($value)) {
      unset($subarray[$key]);
    } 
  }
}

It's simpler with a functional approach:

$array = array_map(
  fn($subarray) => array_filter($subarray),
  $array
);

If the array may have arbitrary levels, you may implement a recursive function:

function remove_empty_recursive(array &$array)
{
  foreach($array as $key => &$value) {
    if (empty($value)) {
      unset($array[$key]);
    } elseif (is_array($value)) {
      remove_empty_recursive($value);
    }
  }
}

Notice all those solutions assume you want to remove "0", 0 and false from the array. Otherwise, you need to specify another criteria, instead of using empty. For instance:

$array = array_map(
  fn($subarray) => array_filter(
    $subarray,
    fn($value) => !empty($value) || is_numeric($value) || $value === false
  ),
  $array
);
  • Related