php - Limit the number of loops through array

650

How can I limit the amount of loops through an array using Smarty? Let's say that there's 32 items in a given array, I'd like to limit the number of loops to 8.

{foreach from=$friend_list key=userId item=userInfo name=friend_list}
    {if $smarty.foreach.friend_list.index % 8 && $smarty.foreach.friend_list.index > 0 }
        </tr><tr>
    {/if}
        <td height='50' width='50'>
            <img border='0' height='50' src='http://graph.facebook.com/{$userInfo.user_uid}/picture' style='display:block;' width='50' />
        </td>
{/foreach}

Thanks

490

Answer

Solution:

{foreach from=$friend_list key=userId item=userInfo name=friend_list}
  {if $smarty.foreach.friend_list.index < 8 }
    {if $smarty.foreach.friend_list.index % 8 && $smarty.foreach.friend_list.index > 0 }
        </tr><tr>
    {/if}
        <td height='50' width='50'>
            <img border='0' height='50' src='http://graph.facebook.com/{$userInfo.user_uid}/picture' style='display:block;' width='50' />
        </td>
  {/if}
{/foreach}

Read this Smarty - foreach loop 10 times and stop

ps: I intentionally left theif block withif $smarty.foreach.friend_list.index % 8 in case if will need more than 8 loops. Otherwise that block could be removed (keeping</tr><tr> intact)

888

Answer

Solution:

add a counter before you open you foreach,

$i=1;

increase the counter on each loop (ie inside the foreach)

if($i = 8) break; 
$i++;

(where 8 is your limit)

you code looks all wrong so I didnt bother placing it in. Sort out the () {} issues

359

Answer

Solution:

Here, that should process the first 8 entries and ignore the rest. Unfortunately, there's no way to break from a Smarty for each.

{foreach from=$friend_list key=userId item=userInfo name=friend_list}
    {if $smarty.foreach.friend_list.iteration < 8}
        <td height='50' width='50'>
            <img border='0' height='50' src='http://graph.facebook.com/{$userInfo.user_uid}/picture' style='display:block;' width='50' />
        </td>
    {/if}
{/foreach}

People are also looking for solutions to the problem: php - Best approach to create Tank_Auth in CI

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.