⊗ppPmUFAdv 205 of 447 menu

Tips for Creating Functions in PHP

  1. Function names should be verbs.
  2. Each function's name should accurately reflect what the function does.
  3. A function should do only what is explicitly implied by its name, and nothing else.
  4. Each function should perform only one action.
  5. Use helper functions inside functions.
  6. It is better not to make the code of functions longer than 10-15 lines.
  7. Long functions are better split into a series of helper functions.
  8. Use common prefixes in function names: show, get, set, calc, create, change, check.
  9. Move duplicate code into functions.

Write what the drawbacks of the following code are and fix them:

<?php function sum($arr) { $res = 0; foreach ($arr as $elem) { $res += $elem; } return $res / count($arr); } ?>

Write what the drawbacks of the following code are and fix them:

<?php function func($arr1, $arr2) { $res1 = 0; foreach (arr as $elem) { $res1 += $elem; } $res2 = 0; foreach (arr as $elem) { $res2 += $elem; } return $res1 / $res2; } ?>

Write what the drawbacks of the following code are and fix them:

<?php function getSum($arr) { $res = 0; foreach ($arr as $elem) { $res *= $elem; } return $res; } ?>
byenru