2

How I can remove all elements of an array that contain just whitespace, not whitespace in an element like "foobar " but just empty array elements like " "?

Thanks.

alex
  • 479,566
  • 201
  • 878
  • 984
A Clockwork Orange
  • 23,913
  • 7
  • 25
  • 28

5 Answers5

6

preg_grep() is your friend.

$array = array("This", " ", "is", " ", "a", " ", "test.");

$array = preg_grep('/^\s*\z/', $array, PREG_GREP_INVERT);

var_dump($array);

CodePad.

This will drop all array members of which the string is blank or only consist of whitespace according to \s character class (spaces, tabs, and line breaks).

Output

array(4) {
  [0]=>
  string(4) "This"
  [2]=>
  string(2) "is"
  [4]=>
  string(1) "a"
  [6]=>
  string(5) "test."
}
Community
  • 1
  • 1
alex
  • 479,566
  • 201
  • 878
  • 984
3
$arr = array("This", " ", "is", " ", "a", " ", "test.");
$result = array();
for($arr as $x) {
     if(!preg_match("/^\s*$/", $x)) $result[] = $x;
}
$arr = $result;
Ry-
  • 218,210
  • 55
  • 464
  • 476
3

This code takes advantage of the callback parameter for array_filter. It will loop the array, call trim() on the value, and remove it if the resulting value evaluates to false. (which an empty string will)

$a = array_filter($a, 'trim');

Dominic Barnes
  • 28,083
  • 8
  • 65
  • 90
0
$array = array('foo','  ','bar ');

foreach ($array as $key => $value) {
    if (trim($value) == '') unset($array[$key]);
}

Array when dumped then contains:

array(2) {
  [0]=>
  string(3) "foo"
  [2]=>
  string(4) "bar "
}
CVM
  • 780
  • 1
  • 6
  • 10
0

foreach($arr as $key=>$value)

{

 if($value=" ")

  {

unset($arr[$key]);

/* optional */ array_values($arr);

  }

}
fingerman
  • 2,440
  • 4
  • 19
  • 24
  • yes... I thought I could to this properly this way... only after linking I found out this WYSIWYG editor doesn't support it, But after getting the links I was lazy. – fingerman Apr 19 '11 at 07:57