在PHP中将具有空值的数组视为真正的“空”

在PHP中将具有空值的数组视为真正的“空”

问题描述:

I have this JSON data:

["","","","","","",""]

When decoded, it turns into:

Array ( [0] => [1] => [2] => [3] => [4] => [5] => [6] => )

When I try to validate using empty() in PHP, it still returns true. I aware that PHP will accept that array as FALSE if it is only empty array: Array().

Actually I intended to replace those empty arrays into an empty string.

How to treat that array with empty string as 'totally empty' array?

Thanks.

我有这个JSON数据: p>

  [“”,  “”,“”,“”,“”,“”,“”,“
  code>  pre> 
 
 

解码后,变为: p>

  Array([0] => [1] => [2] => [3] => [4] => [5] => [6] =>  )
  code>  pre> 
 
 

当我尝试在PHP中使用empty()进行验证时,它仍然返回 true code>。 我知道PHP将接受该数组作为 FALSE code>,如果它只是空数组: Array() code>。 p>

其实我打算 将那些空数组替换为空字符串。 p>

如何将带有空字符串的数组视为“完全空”数组? p>

谢谢。 p> div>

Filter it

$array=array_filter($array);

Without providing any further options, this will remove all empty elements from the array hence your array will become 0 length in this case and it will become true empty that you are looking for.

$array=json_decode('["","","","","","",""]');
$array=array_filter($array);
var_dump(empty($array));  // true

Fiddle

And if you don't want to make any changes to the original array but just want to check if all values are empty you can do

var_dump(empty(array_filter($array))); // true. Original array remains same