daGrevis
daGrevis

Reputation: 21333

What's the simplest way to check that values aren't empty in 2D array?

For example, I have an array like this:

array(4) ( "a" => string(0) "" "b" => string(0) "" "c" => string(0) "" "d" => string(0) "" )

None of given values should be empty.

At the moment, I use this:

if (!empty($_POST['x']['a']) && !empty($_POST['x']['b']) && !empty($_POST['x']['c']) && !empty($_POST['x']['d']))

...and that sucks from readability aspect.

Note: Array is associative.

Upvotes: 2

Views: 796

Answers (4)

hakre
hakre

Reputation: 198118

count(array_filter($_POST['x'])) === 4

Some Explanation: Empty() is the Opposite of a Boolean Variable, array_filter removes all elements that equal false (which is !empty()) and this count must match the expectation of 4 elements then.

If the number of elements is defined by the total of elements submitted (empty or not), use count() instead the magic number:

if (count(array_filter($_POST['x'])) === count($_POST['x']))
{
    echo 'No empty elements in $_POST["x"]!';
}

Upvotes: 6

George Cummins
George Cummins

Reputation: 28926

EDIT: (in response to comments)

You can encapsulate the "uncool" logic in a function and call it with a one-liner:

if ( check_for_empty_values( $_POST ) ) { // Do something }

The encapsulated checking logic:

function check_for_empty_values( $data ) {
    $valid = true;
    foreach ( $data as $element ) {
        if ( is_array( $element) ) {
            foreach ( $element as $subelement ) {
                if ( empty( $subelement ) ) {
                    $valid = false;
                }
            }
        }
    }

    return $valid;
}

Upvotes: 0

Phil
Phil

Reputation: 11175

for($_POST as $key => $value) {
    if( !empty($value) ) {
      // Do stuff.    

    }
}

Upvotes: -2

Fabrizio
Fabrizio

Reputation: 3776

Did you check the array_reduce function ?

function all_empty($v,$w){
   $v .= $w;
   return $v;
}
if(array_reduce($_POST['x'],'all_empty','')==''){

I haven't tested, but you can give this a try

Upvotes: 0

Related Questions