Efficient if / for statement

2 short questions based on trying to make my code more efficient (I think my end quest is to make my entire (rather complex) website based on some kind of MVC framework, but not being a professional programmer, I think it will be a long and steep learning curve.)

  • This code has a way to merge operator if

    and loop for

    to avoid nesting:

    if($fileatt['name']!=null)
    {
      $attachedFiles = "You uploaded the following file(s)\n";
      for($i=0;$i<count($docNames);$i++)
      {
        $attachedFiles = $attachedFiles. " - " . $docNames[$i] . "\n";
      }
    }
    
          

  • At the moment I'm doing the fairly standard task of splitting my $ _POST array from a form submission, "clearing" the content, and storing the elements in separate variables:

    $name = cleanInput($_POST['name']);
    $phone = cleanInput($_POST['phone']);
    $message = cleanInput($_POST['message']);
    ...
    
          

(where cleanInput()

contains striptags()

and mysql_real_escape_string()

)

I thought storing all information in an array might improve my code, but is there a way to apply the function to all (or selected) elements of the array? For example, in R, this is what a function does apply()

.

Alternatively, given that all my variables have the same name as in the array $_POST

, is there a way to generate all the variables dynamically in a loop foreach

? (I know the standard answer when people ask if they can generate variables dynamically, use a hashmap or the like, but I was curious to see if there is a technique I missed)

+3


source to share


5 answers


1) To the first question, how to combine an if and a for loop:

Why do you want to combine this, it will make the code harder to read. If your code requires if

and then a loop for

then show that fact, nothing wrong with that. If you want to make your code more readable, you can write a function named fit, eg. listAttachedFiles()

...

2) When asked about clearing user input:



There is a difference between validating input and escaping. It is good to validate input data for example. if you are expecting a number, then you only accept numbers as input. But the escape should not be done until you know the target system. So leave the input as it is and use the function before writing to the db mysql_real_escape_string()

, before writing to the HTML page use the function htmlspecialchars()

.

Combining evacuation functions ahead of time can result in invalid data. It may become impossible to give a correct representation in a particular target system.

+1


source


You can use extract

and combine it witharray_map

extract(array_map('cleanInput', $_POST), EXTR_SKIP);

echo $name; // outputs name

      

Let's warn that $ _POST is could be

nothing and the user can then post anything to your server and it becomes a variable in your code, so if you have things like

if(empty($varName)) { } // assumes $varName is empty initially

      



You can easily bypass the user by sending $_POST['varName'] = 1

To avoid such mishaps, you can whitelist the array and filter out only the ones you need:

$whitelist = array('name', 'phone', 'message');
$fields = array();

foreach($_POST as $k => $v) {
   if(in_array($k, $whitelist)) $fields[$k] = $v;
}

extract(array_map('cleanInput', $fields));

      

+4


source


Personally, I think the cost of using the "If" statement is worth it to have easy-to-read code. Also, you need to be sure that you are actually using fewer loops, combining, if there is such a way.

I'm not sure if I'm following your second question, but have you looked at extract () and array_walk () yet?

+1


source


Point 1 is premature optimization. And you want the best performance / readability by doing this. (Likewise for using arrays for everything).

Item 2 - AaaarrgghhH! You should only change the representation of the data at the point where it exits PHP using a method appropriate for the purpose, not where it arrives in PHP.

0


source


To make the for loop more efficient , don't use Count () in the condition of your loops.

This is the first thing they teach in school. Because the For loops renegotiate the conditions at each iteration.

$nbOfDocs = count($docNames); //will be much faster
for($i=0;$i<$nbOfDocs;$i++)
{
   $attachedFiles = $attachedFiles. " - " . $docNames[$i] . "\n";
}

      

0


source







All Articles