Use foreach to control array scanning in PHP

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.