Igor Martins
Igor Martins

Reputation: 2047

Why this If conditions is always going to else?

I have this conditions:

 if(!empty($numerofiles)) { // <-- WHEN THIS ARRAY IS EMPTY

                for ($i=0; $i < $numerofiles; $i++) {
                    $allowed =  array('doc','pdf','jpg','jpeg','xls','docx','xlsx');
                    $ext = pathinfo($name, PATHINFO_EXTENSION);
                     // BLA BLA BLA SOME CODE

                    if(in_array($ext,$allowed)) {

                        // BLA BLA SOME CODE

                    } else { // <-- ..IT SEND ME FOR THIS ELSE

                        $this->Comment->delete($this->Comment->id);
                        $this->Session->setFlash('Tipo de arquivo não permitido', 'default', array('class' => 'flash_fail'));
                        $this->redirect(array('action' => 'view', $id));

                    }

                }
        }  else { // <-- BUT THIS SHOULD TO GO HERE

        }
    $this->Session->setFlash('Comentário adicionado com sucesso!', 'default', array('class' => 'flash_sucess'));
    $this->redirect(array('action' => 'view', $id));

When in my first if, $numerofiles is empty, this is sending me for the else of the second if. But, I want that if the $numerofiles is empty its jump and send for the end of the code. What is wrong?

Upvotes: 0

Views: 106

Answers (1)

spiderman
spiderman

Reputation: 11132

Simple

change if(!empty($numerofiles)) to if(empty($numerofiles))

You are checking if it is not empty, whereas what you need to check is if it is empty

Also, You said empty($numerofiles)evaluate to false. This means it is not empty. Then again you put a not operator, so you negate it, now the meanining is 'if it is empty'

The empty() function is used to check whether a variable is empty or not.

Return value

FALSE if var_name has a non-empty and non-zero value.

Value Type : Boolean

List of empty things :

"0" (0 as a string)
0 (0 as an integer)
"" (an empty string)
NULL
FALSE
"" (an empty string)
array() (an empty array)
$var_name; (a variable declared but without a value in a class)

Source

Edit:

looks like you still didn't came out of this issue.

lemme try again..

Step 1: if(!empty($numerofiles)) => if(NOT (number of files is EMPTY))

The key thing here is the boolean value of (number of files is EMPTY)

In your comment , You said empty($numerofiles)evaluate to false

So (number of files is EMPTY) is FALSE

Looking again on Step 1:

if(NOT (FALSE)) => if(TRUE)

So your actual code, for this scenario, for the current input, while execution is if(TRUE)

Since it is if(TRUE), the control goes inside. Agree?

Upvotes: 1

Related Questions