Quantcast
Viewing latest article 3
Browse Latest Browse All 28

Answer by Nabi K.A.Z. for Remove empty array elements

In short:

This is my suggested code:

$myarray =  array_values(array_filter(array_map('trim', $myarray), 'strlen'));

Explanation:

I thinks use array_filter is good, but not enough, because values be like space and \n,... keep in the array and this is usually bad.

So I suggest you use mixture ‍‍array_filter and array_map.

array_map is for trimming, array_filter is for remove empty values, strlen is for keep 0 value, and array_values is for re indexing if you needed.

Samples:

$myarray = array("\r", "\n", "\r\n", "", " ", "0", "a");

// "\r", "\n", "\r\n", " ", "a"
$new1 = array_filter($myarray);

// "a"
$new2 = array_filter(array_map('trim', $myarray));

// "0", "a"
$new3 = array_filter(array_map('trim', $myarray), 'strlen');

// "0", "a" (reindex)
$new4 = array_values(array_filter(array_map('trim', $myarray), 'strlen'));

var_dump($new1, $new2, $new3, $new4);

Results:

array(5) {
  [0]=>
" string(1) "
  [1]=>
  string(1) "
"
  [2]=>
  string(2) "
"
  [4]=>
  string(1) " "
  [6]=>
  string(1) "a"
}
array(1) {
  [6]=>
  string(1) "a"
}
array(2) {
  [5]=>
  string(1) "0"
  [6]=>
  string(1) "a"
}
array(2) {
  [0]=>
  string(1) "0"
  [1]=>
  string(1) "a"
}

Online Test:

http://phpio.net/s/5yg0


Viewing latest article 3
Browse Latest Browse All 28

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>