简体   繁体   中英

can't print from nested foreach loop in php

There's four arrays and four foreach loops. Two foreach within other two foreach loops, and i want to echo an array value from nested foreach loop. But i don't know why this prints nothing in my browser.

  $abc = array('arif'=>50, 'mofiz'=> 60, 'tofiz'=> 90);
  $def = array('arif'=>55, 'mofiz'=> 65, 'tofiz'=> 95);
  $ghi = array('arif'=>58, 'mofiz'=> 68, 'tofiz'=> 98);
  $jkl = array('arif'=>59, 'mofiz'=> 69, 'tofiz'=> 99);

  foreach ($abc as $ab):

      foreach ($def as $de):


          foreach ($ghi as $gh):
              /*** this echo prints nothing ***/
              echo $gh['arif'];
          endforeach;

          foreach ($jkl as $jk):
          endforeach;

      endforeach;

  endforeach;
$ghi = array('arif'=>58, 'mofiz'=> 68, 'tofiz'=> 98);

foreach ($ghi as $gh):
    echo $gh['arif'];
endforeach;

Let's see how this is evaluated:

  1. Put every element of $ghi into gh variable iteratively.
  2. On first iteration $gh equals to 58
  3. On second iteration $gh equals to 68
  4. On third iteration $gh equals to 98
  5. No more elements in $ghi , done.

That's the reason it's not printing anything - because $gh is not an array and doesn't have arif key.

I suggest you read more about how foreach loop works

And I also suggest you to read a few books on code structure, especially Clean Code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM