Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this conditional check overkill?

Tags:

php

$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 function validateUploadedFile returns an array as $result['valid'] == TRUE if it goes through.

Here is the question, does the if statement checks too much? Can I simply check the following instead? I have few PHP language knowledge and don't know whether those checks are necessary or not.

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

Thank you

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;
}
like image 938
q0987 Avatar asked Dec 04 '22 11:12

q0987


1 Answers

It depends on what the function returns in the case where the uploaded file is not valid. This should probably suffice in most cases though:

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

Since:

  • FALSE is empty
  • NULL (or an unset array index) is empty
  • It won't complain, even if $result is an empty array

You could also just do

if (!$result['valid'])

but this will give you E_NOTICE if that element isn't set.

like image 94
Ramon Avatar answered Dec 19 '22 11:12

Ramon