2 short questions based on trying to make my code more efficient (I think my ultimate quest is to make my entire (fairly complex) website based on some sort of MVC framework, but not being a professional programmer, I think that's going to be a long and steep learning curve..)
In this code, is there a way to merge the
if
statement andfor
loop, to avoid the 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 do the fairly standard thing of splitting my $_POST array from a form submission, 'clean' the contents and store the elements in individual variables:
$name = cleanInput($_POST['name']); $phone = cleanInput($_POST['phone']); $message = cleanInput($_POST['message']); ...
(where cleanInput()
contains striptags()
and mysql_real_escape_string()
)
I had thought that keeping all the information in an array might my code more efficient, but is there a way to apply a function to all (or selected) elements of an array? For example, in R, this is what the apply()
function does.
Alternatively, given that all my variables have the same name as in the $_POST
array, is there a way to generate all the variables dynamically in a foreach
loop? (I know the standard answer when people ask if they can dynamically generate variables is to use a hashmap or similar, but I was interested to see if there's a technique I've missed)