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.
- /**
- * QUESTION: Judge the fields of the incoming array parameter $params
- *
- * 1. A, B, C are required fields
- * 2. D, E, F are possible fields
- * 3. Others are Fields that must not be present
- *
- * @author yearnfar
- */
- //Method 1:
- $must = array('A','B','C');
- $maybe = array( 'D','E','F');
- foreach($must as $key) {
- if (!isset($params[$key])) exit("{$key} must!");
- }
- foreach($params as $key => $value) {
- if (!in_array($key, $must)) && in_array($key, $maybe)) {
- exit("{$key} Illegal! ");
- }
- }
-
- //Method 2:
- $fields = array('A' => 1,'B' => 1,'C' => 1,
- 'D' => 0,'E' => 0,'F' => 0);
-
- foreach ($params as $key => $value) {
- if (!isset($fields[$key] )) {
- exit("{$key} is illegal!");
- } elseif ($fields[$key]>0) {
- $fields[$key] = 0;
- }
- }
-
- if (array_sum ($fields)>0) {//or if (max($fields) > 0)
- exit("Missing required fields");
- }
-
- //Method 3:
- $fields = array();
-
- foreach ($params as $key => $value) {
-
- switch ($key) {
- case 'A':
- case 'B':
- case 'C':
- $fields[$key] = 0;
- break;
- case 'D':
- case 'E':
- case 'F':
- break;
- default:
- exit("{$key} is illegal!");
- }
- }
-
- if ( count($fields)!=3) {
- exit("Missing required fields");
- }
Copy code
|