Use foreach to control array scanning in PHP
foreach ($c_f_arr as &$c_f) { if (trim($c_f[0])==trim($char)) { echo "$char is exist
"; $c_f[1]++; echo "hahaha
"; echo "this is cf: $c_f[1]
"; } else { echo "$char is not exist
"; $c_new=array(trim($char),'1'); array_push($c_f_arr, $c_new); $n++; } }
After the inserted value is always displayed, foreach scans the array from the beginning, and inserts it several times... Does foreach have this rule? How can this problem be solved? Still considering...
Reply to discussion (solution)
Is there any expert to guide me? I just learned from PHP for a week ......
The foreach statement repeats an embedded statement group for each element in an array or an object set. The foreach statement is used to cyclically access the set to obtain the required information, but should not be used to change the set content to avoid unpredictable side effects.
There is a logic problem with your writing. you must complete the loop to determine whether the statement exists.
You should think that when the array has the same value, the value of count is increased. If the array does not have this value, the value is increased.
You can write as follows:
Foreach uses break to jump out of the loop
The foreach statement repeats an embedded statement group for each element in an array or an object set. The foreach statement is used to cyclically access the set to obtain the required information, but should not be used to change the set content to avoid unpredictable side effects.
There is a logic problem with your writing. you must complete the loop to determine whether the statement exists.
You should think that when the array has the same value, the value of count is increased. If the array does not have this value, the value is increased.
You can write as follows:
Thank you very much!
Thanks to mystery138. I have a logic problem.