Today and the war five slag the teacher discusses the function return value and throws an exception, I wrote a function to find out if there are certain keys in the array. The result I've summed up is the use of throwing exceptions in the right scenario, and the general function is still using the return value to complete his function.
But there's a lot more to be learned about programming: the same problem, a different angle of view can be used to write code.
<?php//I need to define a function to determine whether the given array contains all the keys I need//according to the requirements, the normal solution function Checkkey ($array, $key) {if (!is_arra Y ($array)) {//not array return false; } $key = Explode (', ', $key); foreach ($key as $k = + $v) {if (!array_key_exists ($v, $array)) {//not in array return false; }} return true; }//The following functional warfare five-slag teacher provides ideas for function Newcheckkey ($array, $key) {if (!is_array ($array)) {return false; } $key = Explode (', ', $key); $array _keys = Array_keys ($array); Removes all keys for the given array $array _intersect = Array_intersect (Array_keys ($array), $key); Calculates all keys for the given array with the key to be checked to intersect if ($array _intersect = = = $key) {return true;//If the intersection is $key itself, $array contains all required keys } return false; }//A very low readability function newCheckKey2 ($array, $key) {if (!is_array ($array)) {return FA Lse } $key = Explode (', ', $key); Return Array_intersect (Array_keys ($array), $key) = = = $key; } $data = [' Zhanwuzha ' = ' renzhewudi ', ' bool ' = ' jintiantuiqunle ']; Var_dump (Checkkey ($data, ' Zhanwuzha,bool ')); True Var_dump (Checkkey ($data, ' Zhanwuzha,bool,halei '));//false Var_dump (Newcheckkey ($data, ' Zhanwuzha,bool ')); True Var_dump (Newcheckkey ($data, ' Zhanwuzha,bool,halei ')); False Var_dump (NewCheckKey2 ($data, ' Zhanwuzha,bool ')); True Var_dump (NewCheckKey2 ($data, ' Zhanwuzha,bool,halei ')); False
By comparing the above code, it is easy to do what I want by using the concept of a set in mathematics. Iterating through the array can also accomplish the functions I need. We may get more solutions when we think more, and it is possible to improve the process by comparing different methods.
In addition, my third function is exactly the same as the second function, but it also reduces the readability of the program by defining two variables less. When it comes to maintenance, the difficulty increases. There is a need to choose between different methods in future programming ^_^
Thinking of a custom function