Home > Backend Development > PHP Tutorial > Interleaving of local variables and global variables in PHP (1) Variables in nested for loops

Interleaving of local variables and global variables in PHP (1) Variables in nested for loops

WBOY
Release: 2016-08-08 09:24:51
Original
1211 people have browsed it

I believe that many students who come from c++/java/c# may make such mistakes:

<?php
  for($i=0;$i<9;$i++)
{
    #some code
    #many many code!...
    for($i=0;$i<8;$i++)
     {
          #some my ugly code
      }
}
?>
Copy after login

There is a big for loop outside. After writing a lot of code, another loop is needed. Everyone thinks I don’t want to throw another i, we do this in other languages, but after doing this in PHP, you will find that the code becomes an infinite loop! What is the reason?

It turns out that the for statement is not a function, but a form of statement. In php, both i are treated as global variables. Every time the loop inside is run, i is reassigned to 7, of course forever. There is no way to break out of the cycle.

My solution is to try to separate the names of the auto-incrementing variables in each for loop, which can greatly avoid this problem. And try to use foreach.

The above introduces the interleaving of local variables and global variables in PHP (1) Variables in nested for loops, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template