Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if array value is empty?

Tags:

php

Here is my array ouput

Array
(
    [1] => 1
    [2] => 2
    [3] =>  
)

How do I know the [3] => is empty?

foreach ($array as $key => $value) {
    if (empty($value))
        echo "$key empty <br/>";
    else
        echo "$key not empty <br/>";
}

My out put showing all is not empty. What is correct way to check is empty?

like image 329
Unknown Error Avatar asked Feb 20 '12 19:02

Unknown Error


2 Answers

An other solution:

$array = array('one', 'two', '');

if(count(array_filter($array)) == count($array)) {
    echo 'OK';
} else {
    echo 'ERROR';
}

http://codepad.org/zF9KkqKl

like image 90
EpokK Avatar answered Oct 11 '22 23:10

EpokK


It works as expected, third one is empty

http://codepad.org/yBIVBHj0

Maybe try to trim its value, just in case that third value would be just a space.

foreach ($array as $key => $value) {
    $value = trim($value);
    if (empty($value))
        echo "$key empty <br/>";
    else
        echo "$key not empty <br/>";
}
like image 42
Martin. Avatar answered Oct 11 '22 22:10

Martin.