Welcome Guest, Not a member yet? Register   Sign In
Break a Foreach Loop
#1

[eluser]georgerobbo[/eluser]
I have a loop coming down from an RSS reader and basically I want to break the loop once it has reached a certain number of entries. How do I do this with PHP?


Code:
<?php foreach ($rss as $item):?>
                                <li><a >get_link(); ?&gt;">&lt;?php echo $item->get_title(); ?&gt;</a></li>
                            &lt;?php endforeach; ?&gt;

I have something along the lines of...
Code:
&lt;?php
$limit = 8;
for($constrict = 1; $constrict <= 10; $constrict++)
if($limit > 8)
{
}
#2

[eluser]n0xie[/eluser]
Code:
if($limit > 8)
{
  break;
}
http://us3.php.net/manual/en/control-str....break.php
#3

[eluser]georgerobbo[/eluser]
Thanks, but I'm having trouble applying the break to the foreach loop.
#4

[eluser]n0xie[/eluser]
[quote author="georgerobbo" date="1252531753"]Thanks, but I'm having trouble applying the break to the foreach loop.[/quote]
Trouble how?
#5

[eluser]georgerobbo[/eluser]
I don't understand how to break the loop after eight entries.
#6

[eluser]brianw1975[/eluser]
I think you should fix your query so that $items is only as big as you need. It's detrimental to get 100 rows if you are only going to show 8 of them

Code:
$this->db->limit(8);

@noxie: not have your coffee yet? lol $limit is not being updated anywhere, i think you mean
Code:
if($constrict >= 8)
{
  break;
}

As for the second example another(better?) way would be :
Code:
&lt;?php
$limit = 8;
for($constrict = 1; $constrict <= $limit; $constrict++)
{}
#7

[eluser]georgerobbo[/eluser]
I'm using SimplePie to read RSS feeds off the New Scientist website but I can't find the variable to limit the number of feeds displayed, the documentation only helps if your using multiple feeds.
#8

[eluser]brianw1975[/eluser]
ok, it's pretty easy

Code:
&lt;?php $limit = 8; ?&gt;
&lt;?php foreach ($rss as $item):?&gt;
&lt;?php $counter++; ?&gt;
<li><a >get_link(); ?&gt;">&lt;?php echo $item->get_title(); ?&gt;</a></li>
&lt;?php if($counter >= $limit) break; ?&gt;
&lt;?php endforeach; ?&gt;

i think.... i don't use the alternative foreach syntax
#9

[eluser]n0xie[/eluser]
[quote author="brianw1975" date="1252532260"]
@noxie: not have your coffee yet? lol $limit is not being updated anywhere, i think you mean
[/quote]
No, I genuinely did not understand how one could not get 'break' to work.
#10

[eluser]überfuzz[/eluser]
First of all, where do you get the $css array? Could you show how it, print_r().

The best solution would probably be to render $rss right from starters. But you could use this as simple fix until you do.
Code:
$rss_temp = array_chunk($rss ,8 ,TRUE);
$rss_chunk = $rss_temp[0];




Theme © iAndrew 2016 - Forum software by © MyBB