1

I'm using the following

if (!empty($data['var_1']) 
 && !empty($data['var_2']) 
 && !empty($data['var_3']) 
 && !empty($data['var_4'])
 && !empty($data['var_5']) 
 && !empty($data['var_6']) 
 && !empty($data['var_7']) 
 && !empty($data['var_8']) 
 && !empty($data['var_9'])) {
//BLOCK HERE
}

Basically, what I'm trying to achieve is if all of the variables are empty, hide the block. If 8 or less are empty, display the block.

Where am I going wrong?

2
  • 2
    i m not getting ur question correctly.. can you please give some more idea Commented Oct 1, 2012 at 12:57
  • Can $var_x be an array, or are they entirely separate variables? Is this data from a form? A bit more background would be helpful. Commented Oct 1, 2012 at 13:00

7 Answers 7

1

You want || not &&. This will display the block only if they are all not empty. I think there is probably a nicer way to do this, though, like array_filter.

Sign up to request clarification or add additional context in comments.

Comments

1

Well, you could just use a loop and an $isok variable:

$isok = false;
for($i=1; $i<10; $i++) {
    if( !empty($data['var_'.$i])) {
        $isok = true;
        break; // no need to continue looping
    }
}
if( $isok) {
    // BLOCK HERE
}

This is easier to edit too, in case you change the var_ part or want a different range of numbers.

Comments

1

You can also try

$data = array_filter($data); // remove all empty value form array

if (count($data)) {
    // do your thing
}

Comments

0

The code you wrote will display the block if ALL of the variables aren't empty. If you want it to be displayed when ANY of the variable isn't empty, use OR instead of AND by replacing the && by ||.

<?php
if (!empty($data['var_1']) || !empty($data['var_2']) || !empty($data['var_3']) || !empty($data['var_4']) || !empty($data['var_5']) || !empty($data['var_6']) || !empty($data['var_7']) || !empty($data['var_8']) || !empty($data['var_9'])) {
    //BLOCK HERE
}

Comments

0

You can use array_values() for that:

if ( count(array_values($data)) ) {
    //BLOCK HERE
}

Comments

0

Replace && (AND) with || (OR)

if (!empty($data['var_1']) 
 || !empty($data['var_2']) 
 || !empty($data['var_3']) 
 || !empty($data['var_4'])
 || !empty($data['var_5']) 
 || !empty($data['var_6']) 
 || !empty($data['var_7']) 
 || !empty($data['var_8']) 
 || !empty($data['var_9'])) {
//BLOCK HERE
}

Comments

0
if (empty(array_values($data))) { /* will return you true if all variables are empty*/}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.