phparraysis-empty

Validate an array as "empty" if it has no elements or if all elements have no length


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?


Solution

  • 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