# Use filter_var_array on whole array, or inside iteration

I have a MySQL result set in a PHP multidimensional array.

I want to iterate through it and output it sanitized. Considering the two alternatives below, are there any performance differences?

filter_var_array on the whole result set before iterating:

$sql_rows = filter_var_array($sql_rows, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
foreach ($sql_rows as$sql_row) {
print '<p>' . $sql_row['first_name'] .$sql_row['last_name'] . '</p>';
}


filter_var_array on each row inside the iteration:

foreach ($sql_rows as$sql_row) {
$sql_row = filter_var_array($sql_row, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
print '<p>' . $sql_row['first_name'] .$sql_row['last_name'] . '</p>';
}

• It could go either way. On one hand, you run a function once, on the other you run it multiple times but on much smaller pieces. I'm not sure which would be the better bet for you. I'd try both, wrap microtime()s around each and see how long it took to perform each and then use whichever had better performance. – mseancole Jul 11 '12 at 13:34

1. I'd call the filtered variable something which shows that the data has been filtered, like $filtered_row. It would improve readability and help maintainers. 2. The code prints the first name and the last name without any separator character. I'd consider printing a separator there: print '<p>' .$sql_row['first_name'] . ' ' . $sql_row['last_name'] . '</p>';  3. If you use only the first_name and the last_name maybe you should only filter these fields not the whole array. (I don't know whether it contains other values or not.) 4. Consider memory usage too. If I'm right the first one have to store the input and output array in the memory during the filtering which needs two times of the array size of memory temporarily. In the second case it's much smaller since it filters only one row at a time so it needs memory for the array once and two times of the size of a row during the filtering. • Instead of: print '<p>' .$sql_row['first_name'] . ' ' . $sql_row['last_name'] . '</p>'; do: echo "<p>{$sql_row['first_name']} {$sql_row['last_name']}</p>"; - it's considerably more readable. – Ariel Jul 11 '12 at 23:53 • Many interesting and insightful points in your answer, thanks a lot! – elaxsj Jul 12 '12 at 13:16 Instead of: print '<p>' .$sql_row['first_name'] . ' ' . $sql_row['last_name'] . '</p>';  do: echo "<p>{$sql_row['first_name']} {\$sql_row['last_name']}</p>";