Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to ignore first loop and continue from second in foreach?

Tags:

php

I use foreach loop but it always gives an wierd result in the first but others are fine so i want to remove 1st loop and continue from 2nd...

My code is

foreach($doc->getElementsByTagName('a') as $a){
foreach($a->getElementsByTagName('img') as $img){
   echo $a->getAttribute('href');
   echo $img->src . '<br>';
}
}
like image 1000
Naveen Gamage Avatar asked May 05 '12 19:05

Naveen Gamage


People also ask

How do you skip elements in foreach loop?

The answer here is to use foreach with a LimitIterator . Show activity on this post. The continue causes the foreach to skip back to the beginning and move on to the next element in the array. It's extremely useful for disregarding parts of an array which you don't want to be processed in a foreach loop.

Does Break stop foreach?

break ends execution of the current for , foreach , while , do-while or switch structure.


2 Answers

$counter = 0;

foreach($doc->getElementsByTagName('a') as $a){
foreach($a->getElementsByTagName('img') as $img){

   if ($counter++ == 0) continue;

   echo $a->getAttribute('href');
   echo $img->src . '<br>';
}
}
like image 184
Sarfraz Avatar answered Nov 15 '22 04:11

Sarfraz


The simplest way I can think of in order to skip the first loop is by using a flag

ex:

 $b = false;
 foreach( ...) {
    if(!$b) {       //edited for accuracy
       $b = true;
       continue;
    }
 }
like image 42
Abu Romaïssae Avatar answered Nov 15 '22 04:11

Abu Romaïssae