This article mainly introduces the performance comparison of using in_array () foreacharray_search () in php to find whether an array contains data. if you need to know whether a character contains an array, there are many ways to solve this problem. new users who are just learning php tend to use loops to solve the problem. for small websites, this solution will not cause any major problems. However, in terms of performance, this method is not the best method. I will compare the performance differences between the three methods, foreach and in_array () array_search.
Start (); $ a = 'K'; $ B = array ('A', 'B', 'C', 'D', 'e', 'e', 'F ', 'G', 'H', 'I', 'J', 'k');/* for ($ I = 0; $ I <100000; $ I ++) {var_dump (in_array ($ a, $ B) ;}* // * for ($ I = 0; $ I <100000; $ I ++) {foreach ($ B as $ key =>$ value) {if ($ a ==$ value) {// echo TRUE; continue ;}}} * // * for ($ I = 0; $ I <100000; $ I ++) {array_search ($ a, $ B );} */$ runtime-> stop (); echoThere are many methods to determine whether a character is included in an array. new users who are just learning php tend to use loops. for small websites, this solution will not cause any major problems. However, in terms of performance, this method is not the best method. I will compare the performance differences between the three methods, foreach and in_array () array_search.
___FCKpd___0
The execution time of the above programs is shown in:
In_array ()
Foreach
Array_search ()
From the above, we can roughly see the performance of these three methods. array_search and in_array are similar, and foreach is the worst.
B; echo "Execution time :". $ runtime-> spent (). "millisecond"; class runtime {var $ StartTime = 0; var $ StopTime = 0; function get_microtime () {list ($ usec, $ sec) = explode ('', microtime (); return (float) $ usec + (float) $ sec);} function start () {$ this-> StartTime = $ this-> get_microtime ();} function stop () {$ this-> StopTime = $ this-> get_microtime ();} function spent () {return round ($ this-> StopTime-$ this-> StartTime) * 1 000, 1) ;}}?>
The execution time of the above programs is shown in:
In_array ()
Foreach
Array_search ()
From the above, we can roughly see the performance of these three methods. array_search and in_array are similar, and foreach is the worst.