Is this conditional check redundant?

$ result = validateUploadedFile ($ _ FILES);

if (!empty($result) && !empty($result['valid']) && $result['valid']) { // do sth // I don't know why sometime this three checks will cause me problems // In other words, even if $result['valid'] is TRUE, this scope will not be hit } 

The validateUploadedFile function returns an array as $ result ['valid'] == TRUE if it passes.

The question is, is the if statement checked too much? Can I just check the following? I have little knowledge of the PHP language and don’t know if these checks are necessary or not.

 if ( $result['valid'] ) { // do sth } 

thanks

 function validateUploadedFile($uploadedFile) { // Define file size limit $result = array('valid' => FALSE, 'error_message' => null, 'error_code' => null); if (sth_wrong) { $result['error_message'] = 'sth_wrong'; return $result; } if (sth_wrong2) { $result['error_message'] = 'sth_wrong2'; return $result; } $result['valid'] = TRUE; return $result; } 
+4
source share
4 answers

It depends on what the function returns if the downloaded file is invalid. In most cases, this should be sufficient:

 if (!empty($result['valid'])) 

FROM

  • FALSE empty
  • NULL (or index of an unset array) empty
  • It will not complain even if $result is an empty array

You can also just do

 if (!$result['valid']) 

but it will give you E_NOTICE if this item is not set.

+10
source

I would think

 if (isset($result['valid']) && $result['valid']) 

will work fine.

+4
source

Your approach is more than what you should do with raw user input. However, since you are dealing with a function, it would be much easier to make it heavy.

Just make sure it always sets the key to 'valid' ; your code will be more readable and safe. If you do this, if($result['valid']) sufficient.

+2
source

You can check it out. In this particular case, it seems that you are not quite sure which values ​​need to be checked. In most cases, and according to logic, just doing a! $ Result ['valid'] / should / work, but assuming PHP considers null / unset values ​​to be false.

Make a quick script that checks all conditions separately.

  • What happens when calling empty ($ result ['valid']) when $ result is null?
  • What happens when you call! $ result ['valid'] when $ result ['valid'] is undefined?

Go on. Write a script. Check it out and know.

+1
source

All Articles