Judge the fields of the incoming array parameters

WBOY
Release: 2016-07-25 08:47:32
Original
950 people have browsed it
Judge the fields of the incoming array parameters. A, B, and C are required fields, D, E, and F are possible fields, and other fields must not be present.
  1. /**
  2. * QUESTION: Judge the fields of the incoming array parameter $params
  3. *
  4. * 1. A, B, C are required fields
  5. * 2. D, E, F are possible fields
  6. * 3. Others are Fields that must not be present
  7. *
  8. * @author yearnfar
  9. */
  10. //Method 1:
  11. $must = array('A','B','C');
  12. $maybe = array( 'D','E','F');
  13. foreach($must as $key) {
  14. if (!isset($params[$key])) exit("{$key} must!");
  15. }
  16. foreach($params as $key => $value) {
  17. if (!in_array($key, $must)) && in_array($key, $maybe)) {
  18. exit("{$key} Illegal! ");
  19. }
  20. }
  21. //Method 2:
  22. $fields = array('A' => 1,'B' => 1,'C' => 1,
  23. 'D' => 0,'E' => 0,'F' => 0);
  24. foreach ($params as $key => $value) {
  25. if (!isset($fields[$key] )) {
  26. exit("{$key} is illegal!");
  27. } elseif ($fields[$key]>0) {
  28. $fields[$key] = 0;
  29. }
  30. }
  31. if (array_sum ($fields)>0) {//or if (max($fields) > 0)
  32. exit("Missing required fields");
  33. }
  34. //Method 3:
  35. $fields = array();
  36. foreach ($params as $key => $value) {
  37. switch ($key) {
  38. case 'A':
  39. case 'B':
  40. case 'C':
  41. $fields[$key] = 0;
  42. break;
  43. case 'D':
  44. case 'E':
  45. case 'F':
  46. break;
  47. default:
  48. exit("{$key} is illegal!");
  49. }
  50. }
  51. if ( count($fields)!=3) {
  52. exit("Missing required fields");
  53. }
Copy code


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!