Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

executing foreach loop only once [closed]

Tags:

foreach

php

As we know foreach loop will execute till condition does not become false. I want to execute it only once.

$i=0;
foreach($html->find('img') as $element) 
{    

       if($i!=0)  
          break;
       $logo= $element->src . '<br>';
       $i++;
}

Is there any other solution for this? like foronce in place of foreach?

like image 396
user123 Avatar asked Dec 12 '13 13:12

user123


People also ask

How do you run a loop only once?

Initialisation part of for loop executes only once. int I=0 executes only once. That i=0 statement would execute only once.

Can a foreach loop be infinite?

You cannot make an infinite foreach loop. foreach is specifically for iterating through a collection. If that's not what you want, you should not be using foreach .


1 Answers

As we know foreach loop will execute till condition does not become false.

A foreach loop will execute once for every item of the container unless a return or break condition is defined within the foreach block.

I want to execute it only once.

Loops that executes once are called "don't use a loop in the first place". Here's your example fixed:

$logo = $html->find('img')[0]->src . '<br>';
like image 148
Shoe Avatar answered Nov 02 '22 19:11

Shoe