'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>';
}
}
Solution 1:[1]
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;
}
}
Solution 2:[2]
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>';
}
}
Solution 3:[3]
$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;
}
Solution 4:[4]
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.
Solution 5:[5]
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>';
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Data2700 |
| Solution 2 | swapnilsarwe |
| Solution 3 | mgraph |
| Solution 4 | ericksho |
| Solution 5 | Amit Sharma |
