Naveen Gamage
Naveen Gamage

Reputation: 1884

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

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>';
}
}

Upvotes: 6

Views: 27304

Answers (6)

Sive.Host
Sive.Host

Reputation: 11

You could also try array slice in PHP:

foreach(array_slice($doc->getElementsByTagName('a'),1) as $a){
   foreach(array_slice($a->getElementsByTagName('img'),1) as $img){
      echo $a->getAttribute('href');
      echo $img->src . '<br>';
   }
}

Upvotes: 1

Sarfraz
Sarfraz

Reputation: 382696

$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>';
}
}

Upvotes: 18

ericksho
ericksho

Reputation: 367

If you don't wanna define an extra counter:

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

        if ( $a === reset( $doc->getElementsByTagName('a') ) && $img === reset( $a->getElementsByTagName('img') ) ) continue;

       echo $a->getAttribute('href');
       echo $img->src . '<br>';
    }
}

I don't know which will perform better.

Upvotes: 0

Abu Roma&#239;ssae
Abu Roma&#239;ssae

Reputation: 3901

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;
    }
 }

Upvotes: 14

swapnilsarwe
swapnilsarwe

Reputation: 1300

try something like this

foreach($doc->getElementsByTagName('a') as $a)
{
    $count = 0;
    foreach($a->getElementsByTagName('img') as $img)
    {
        if(count == 0)
        {
            $count++;
            continue;
        }
        echo $a->getAttribute('href');
        echo $img->src . '<br>';
    }
}

Upvotes: 3

mgraph
mgraph

Reputation: 15338

$nm = 0;
foreach($doc->getElementsByTagName('a') as $a){
  if($nm == 1){
    foreach($a->getElementsByTagName('img') as $img){
       echo $a->getAttribute('href');
       echo $img->src . '<br>';
    }
  }
  $nm=1;
}

Upvotes: 1

Related Questions