PageRenderTime 53ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/documentation/en/designers/language-builtin-functions/language-function-foreach.xml

https://bitbucket.org/hallgrennetworks/smarty
XML | 531 lines | 470 code | 40 blank | 21 comment | 0 complexity | 0c19ad488b692b124b85684ab6527263 MD5 | raw file
Possible License(s): LGPL-3.0
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!-- $Revision$ -->
  3. <sect1 id="language.function.foreach">
  4. <title>{foreach},{foreachelse}</title>
  5. <para>
  6. <varname>{foreach}</varname> is used for looping over arrays of data. <varname>{foreach}</varname> has a simpler and cleaner syntax than the <link linkend="language.function.section"><varname>{section}</varname></link> loop, and can also loop over associative arrays.
  7. </para>
  8. <para>
  9. <varname>{foreach $arrayvar as $itemvar}</varname>
  10. </para>
  11. <para>
  12. <varname>{foreach $arrayvar as $keyvar=>$itemvar}</varname>
  13. </para>
  14. <note>
  15. <para>
  16. This foreach syntax does not accept any named attributes. This syntax is new to Smarty 3, however the Smarty 2.x syntax <literal>{foreach from=$myarray key="mykey" item="myitem"}</literal> is still supported.
  17. </para>
  18. </note>
  19. <itemizedlist>
  20. <listitem><para>
  21. <varname>{foreach}</varname> loops can be nested.
  22. </para></listitem>
  23. <listitem><para>
  24. The <parameter>array</parameter> variable, usually an array of values,
  25. determines the number of times <varname>{foreach}</varname> will loop. You can also pass an integer for arbitrary loops.
  26. </para></listitem>
  27. <listitem><para>
  28. <varname>{foreachelse}</varname> is executed when there are no
  29. values in the <parameter>array</parameter> variable.
  30. </para></listitem>
  31. <listitem>
  32. <para>
  33. <varname>{foreach}</varname> properties are
  34. <link linkend="foreach.property.index"><parameter>@index</parameter></link>,
  35. <link linkend="foreach.property.iteration"><parameter>@iteration</parameter></link>,
  36. <link linkend="foreach.property.first"><parameter>@first</parameter></link>,
  37. <link linkend="foreach.property.last"><parameter>@last</parameter></link>,
  38. <link linkend="foreach.property.show"><parameter>@show</parameter></link>,
  39. <link linkend="foreach.property.total"><parameter>@total</parameter></link>.
  40. </para>
  41. </listitem>
  42. <listitem>
  43. <para>
  44. <varname>{foreach}</varname> constructs are
  45. <link linkend="foreach.construct.break"><varname>{break}</varname></link>,
  46. <link linkend="foreach.construct.continue"><varname>{continue}</varname></link>.
  47. </para>
  48. </listitem>
  49. <listitem><para>
  50. Instead of specifying the <parameter>key</parameter> variable you can access the current key of the
  51. loop item by <parameter>{$item@key}</parameter> (see examples below).
  52. </para></listitem>
  53. </itemizedlist>
  54. <note>
  55. <para>
  56. The <literal>$var@property</literal> syntax is new to Smarty 3, however when using the Smarty 2 <literal>{foreach from=$myarray key="mykey" item="myitem"}</literal> style syntax, the <literal>$smarty.foreach.name.property</literal> syntax is still supported.
  57. </para>
  58. </note>
  59. <note>
  60. <para>
  61. Although you can retrieve the array key with the syntax <literal>{foreach $myArray as $myKey => $myValue}</literal>, the key is always available as <varname>$myValue@key</varname> within the foreach loop.
  62. </para>
  63. </note>
  64. <para><emphasis role="bold">Option Flags:</emphasis></para>
  65. <informaltable frame="all">
  66. <tgroup cols="2">
  67. <colspec colname="param" align="center" />
  68. <colspec colname="desc" />
  69. <thead>
  70. <row>
  71. <entry>Name</entry>
  72. <entry>Description</entry>
  73. </row>
  74. </thead>
  75. <tbody>
  76. <row>
  77. <entry>nocache</entry>
  78. <entry>Disables caching of the <varname>{foreach}</varname> loop</entry>
  79. </row>
  80. </tbody>
  81. </tgroup>
  82. </informaltable>
  83. <example>
  84. <title>A simple <varname>{foreach}</varname> loop</title>
  85. <programlisting role="php">
  86. <![CDATA[
  87. <?php
  88. $arr = array('red', 'green', 'blue');
  89. $smarty->assign('myColors', $arr);
  90. ?>
  91. ]]>
  92. </programlisting>
  93. <para>Template to output <parameter>$myColors</parameter> in an un-ordered list</para>
  94. <programlisting>
  95. <![CDATA[
  96. <ul>
  97. {foreach $myColors as $color}
  98. <li>{$color}</li>
  99. {/foreach}
  100. </ul>
  101. ]]>
  102. </programlisting>
  103. <para>
  104. The above example will output:
  105. </para>
  106. <screen>
  107. <![CDATA[
  108. <ul>
  109. <li>red</li>
  110. <li>green</li>
  111. <li>blue</li>
  112. </ul>
  113. ]]>
  114. </screen>
  115. </example>
  116. <example>
  117. <title>Demonstrates the an additional <parameter>key</parameter> variable</title>
  118. <programlisting role="php">
  119. <![CDATA[
  120. <?php
  121. $people = array('fname' => 'John', 'lname' => 'Doe', 'email' => 'j.doe@example.com');
  122. $smarty->assign('myPeople', $people);
  123. ?>
  124. ]]>
  125. </programlisting>
  126. <para>Template to output <parameter>$myArray</parameter> as key/value pairs.</para>
  127. <programlisting>
  128. <![CDATA[
  129. <ul>
  130. {foreach $myPeople as $value}
  131. <li>{$value@key}: {$value}</li>
  132. {/foreach}
  133. </ul>
  134. ]]>
  135. </programlisting>
  136. <para>
  137. The above example will output:
  138. </para>
  139. <screen>
  140. <![CDATA[
  141. <ul>
  142. <li>fname: John</li>
  143. <li>lname: Doe</li>
  144. <li>email: j.doe@example.com</li>
  145. </ul>
  146. ]]>
  147. </screen>
  148. </example>
  149. <example>
  150. <title>{foreach} with nested <parameter>item</parameter> and <parameter>key</parameter></title>
  151. <para>Assign an array to Smarty, the key contains the key for each looped value.</para>
  152. <programlisting role="php">
  153. <![CDATA[
  154. <?php
  155. $smarty->assign('contacts', array(
  156. array('phone' => '555-555-1234',
  157. 'fax' => '555-555-5678',
  158. 'cell' => '555-555-0357'),
  159. array('phone' => '800-555-4444',
  160. 'fax' => '800-555-3333',
  161. 'cell' => '800-555-2222')
  162. ));
  163. ?>
  164. ]]>
  165. </programlisting>
  166. <para>The template to output <parameter>$contact</parameter>.</para>
  167. <programlisting>
  168. <![CDATA[
  169. {* key always available as a property *}
  170. {foreach $contacts as $contact}
  171. {foreach $contact as $value}
  172. {$value@key}: {$value}
  173. {/foreach}
  174. {/foreach}
  175. {* accessing key the PHP syntax alternate *}
  176. {foreach $contacts as $contact}
  177. {foreach $contact as $key => $value}
  178. {$key}: {$value}
  179. {/foreach}
  180. {/foreach}
  181. ]]>
  182. </programlisting>
  183. <para>
  184. Either of the above examples will output:
  185. </para>
  186. <screen>
  187. <![CDATA[
  188. phone: 555-555-1234
  189. fax: 555-555-5678
  190. cell: 555-555-0357
  191. phone: 800-555-4444
  192. fax: 800-555-3333
  193. cell: 800-555-2222
  194. ]]>
  195. </screen>
  196. </example>
  197. <example>
  198. <title>Database example with {foreachelse}</title>
  199. <para>A database (PDO) example of looping over search results. This example is looping over a PHP iterator instead of an array().</para>
  200. <programlisting role="php">
  201. <![CDATA[
  202. <?php
  203. include('Smarty.class.php');
  204. $smarty = new Smarty;
  205. $dsn = 'mysql:host=localhost;dbname=test';
  206. $login = 'test';
  207. $passwd = 'test';
  208. // setting PDO to use buffered queries in mysql is
  209. // important if you plan on using multiple result cursors
  210. // in the template.
  211. $db = new PDO($dsn, $login, $passwd, array(
  212. PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true));
  213. $res = $db->prepare("select * from users");
  214. $res->execute();
  215. $res->setFetchMode(PDO::FETCH_LAZY);
  216. // assign to smarty
  217. $smarty->assign('res',$res);
  218. $smarty->display('index.tpl');?>
  219. ?>
  220. ]]>
  221. </programlisting>
  222. <programlisting>
  223. <![CDATA[
  224. {foreach $res as $r}
  225. {$r.id}
  226. {$r.name}
  227. {foreachelse}
  228. .. no results ..
  229. {/foreach}
  230. ]]>
  231. </programlisting>
  232. </example>
  233. <para>
  234. The above is assuming the results contain the columns named <literal>id</literal> and <literal>name</literal>.
  235. </para>
  236. <para>
  237. What is the advantage of an iterator vs. looping over a plain old array? With an array, all the results are accumulated into memory before being looped. With an iterator, each result is loaded/released within the loop. This saves processing time and memory, especially for very large result sets.
  238. </para>
  239. <sect2 id="foreach.property.index">
  240. <title>@index</title>
  241. <para>
  242. <parameter>index</parameter> contains the current array index, starting with zero.
  243. </para>
  244. <example>
  245. <title><parameter>index</parameter> example</title>
  246. <programlisting>
  247. <![CDATA[
  248. {* output empty row on the 4th iteration (when index is 3) *}
  249. <table>
  250. {foreach $items as $i}
  251. {if $i@index eq 3}
  252. {* put empty table row *}
  253. <tr><td>nbsp;</td></tr>
  254. {/if}
  255. <tr><td>{$i.label}</td></tr>
  256. {/foreach}
  257. </table>
  258. ]]>
  259. </programlisting>
  260. </example>
  261. </sect2>
  262. <sect2 id="foreach.property.iteration">
  263. <title>@iteration</title>
  264. <para>
  265. <parameter>iteration</parameter> contains the current loop iteration and always
  266. starts at one, unlike <link linkend="foreach.property.index"><parameter>index</parameter></link>.
  267. It is incremented by one on each iteration.
  268. </para>
  269. <example>
  270. <title><parameter>iteration</parameter> example: is div by</title>
  271. <para>
  272. The <emphasis>"is div by"</emphasis> operator can be used to detect a specific iteration. Here we bold-face the name every 4th iteration.
  273. </para>
  274. <programlisting>
  275. <![CDATA[
  276. {foreach $myNames as $name}
  277. {if $name@iteration is div by 4}
  278. <b>{$name}</b>
  279. {/if}
  280. {$name}
  281. {/foreach}
  282. ]]>
  283. </programlisting>
  284. </example>
  285. <example>
  286. <title><parameter>iteration</parameter> example: is even/odd by</title>
  287. <para>
  288. The <emphasis>"is even by"</emphasis> and <emphasis>"is odd by"</emphasis> operators can be used to alternate something every so many iterations. Choosing between even or odd rotates which one starts. Here we switch the font color every 3rd iteration.
  289. </para>
  290. <programlisting>
  291. <![CDATA[
  292. {foreach $myNames as $name}
  293. {if $name@iteration is even by 3}
  294. <span style="color: #000">{$name}</span>
  295. {else}
  296. <span style="color: #eee">{$name}</span>
  297. {/if}
  298. {/foreach}
  299. ]]>
  300. </programlisting>
  301. <para>
  302. This will output something similar to this:
  303. </para>
  304. <screen>
  305. <![CDATA[
  306. <span style="color: #000">...</span>
  307. <span style="color: #000">...</span>
  308. <span style="color: #000">...</span>
  309. <span style="color: #eee">...</span>
  310. <span style="color: #eee">...</span>
  311. <span style="color: #eee">...</span>
  312. <span style="color: #000">...</span>
  313. <span style="color: #000">...</span>
  314. <span style="color: #000">...</span>
  315. <span style="color: #eee">...</span>
  316. <span style="color: #eee">...</span>
  317. <span style="color: #eee">...</span>
  318. ...
  319. ]]>
  320. </screen>
  321. </example>
  322. </sect2>
  323. <sect2 id="foreach.property.first">
  324. <title>@first</title>
  325. <para>
  326. <parameter>first</parameter> is &true; if the current <varname>{foreach}</varname>
  327. iteration is the initial one. Here we display a table header row on the first iteration.
  328. </para>
  329. <example>
  330. <title><parameter>first</parameter> property example</title>
  331. <programlisting>
  332. <![CDATA[
  333. {* show table header at first iteration *}
  334. <table>
  335. {foreach $items as $i}
  336. {if $i@first}
  337. <tr>
  338. <th>key</td>
  339. <th>name</td>
  340. </tr>
  341. {/if}
  342. <tr>
  343. <td>{$i@key}</td>
  344. <td>{$i.name}</td>
  345. </tr>
  346. {/foreach}
  347. </table>
  348. ]]>
  349. </programlisting>
  350. </example>
  351. </sect2>
  352. <sect2 id="foreach.property.last">
  353. <title>@last</title>
  354. <para>
  355. <parameter>last</parameter> is set to &true; if the current
  356. <varname>{foreach}</varname> iteration is the final one. Here we display a horizontal rule on the last iteration.
  357. </para>
  358. <example>
  359. <title><parameter>last</parameter> property example</title>
  360. <programlisting>
  361. <![CDATA[
  362. {* Add horizontal rule at end of list *}
  363. {foreach $items as $item}
  364. <a href="#{$item.id}">{$item.name}</a>{if $item@last}<hr>{else},{/if}
  365. {foreachelse}
  366. ... no items to loop ...
  367. {/foreach}
  368. ]]>
  369. </programlisting>
  370. </example>
  371. </sect2>
  372. <sect2 id="foreach.property.show">
  373. <title>@show</title>
  374. <para>
  375. The show <parameter>show</parameter> property can be used after the execution of a
  376. <varname>{foreach}</varname> loop to detect if data has been displayed or not.
  377. <parameter>show</parameter> is a boolean value.
  378. </para>
  379. <example>
  380. <title><parameter>show</parameter> property example</title>
  381. <programlisting>
  382. <![CDATA[
  383. <ul>
  384. {foreach $myArray as $name}
  385. <li>{$name}</li>
  386. {/foreach}
  387. </ul>
  388. {if $name@show} do something here if the array contained data {/if}
  389. ]]>
  390. </programlisting>
  391. </example>
  392. </sect2>
  393. <sect2 id="foreach.property.total">
  394. <title>@total</title>
  395. <para>
  396. <parameter>total</parameter> contains the number of iterations that this
  397. <varname>{foreach}</varname> will loop.
  398. This can be used inside or after the <varname>{foreach}</varname>.
  399. </para>
  400. <example>
  401. <title><parameter>total</parameter> property example</title>
  402. <programlisting>
  403. <![CDATA[
  404. {* show number of rows at end *}
  405. {foreach $items as $item}
  406. {$item.name}<hr/>
  407. {if $item@last}
  408. <div id="total">{$item@total} items</div>
  409. {/if}
  410. {foreachelse}
  411. ... no items to loop ...
  412. {/foreach}
  413. ]]>
  414. </programlisting>
  415. </example>
  416. <para>
  417. See also <link linkend="language.function.section"><varname>{section}</varname></link>,
  418. <link linkend="language.function.for"><varname>{for}</varname></link>
  419. and
  420. <link linkend="language.function.while"><varname>{while}</varname></link>
  421. </para>
  422. </sect2>
  423. <sect2 id="foreach.construct.break">
  424. <title>{break}</title>
  425. <para>
  426. <varname>{break}</varname> aborts the iteration of the array
  427. </para>
  428. <example>
  429. <title><varname>{break}</varname> example</title>
  430. <programlisting>
  431. <![CDATA[
  432. {$data = [1,2,3,4,5]}
  433. {foreach $data as $value}
  434. {if $value == 3}
  435. {* abort iterating the array *}
  436. {break}
  437. {/if}
  438. {$value}
  439. {/foreach}
  440. {*
  441. prints: 1 2
  442. *}
  443. ]]>
  444. </programlisting>
  445. </example>
  446. </sect2>
  447. <sect2 id="foreach.construct.continue">
  448. <title>{continue}</title>
  449. <para>
  450. <varname>{continue}</varname> leaves the current iteration and begins with the next iteration.
  451. </para>
  452. <example>
  453. <title><varname>{continue}</varname> example</title>
  454. <programlisting>
  455. <![CDATA[
  456. {$data = [1,2,3,4,5]}
  457. {foreach $data as $value}
  458. {if $value == 3}
  459. {* skip this iteration *}
  460. {continue}
  461. {/if}
  462. {$value}
  463. {/foreach}
  464. {*
  465. prints: 1 2 4 5
  466. *}
  467. ]]>
  468. </programlisting>
  469. </example>
  470. </sect2>
  471. </sect1>
  472. <!-- Keep this comment at the end of the file
  473. Local variables:
  474. mode: sgml
  475. sgml-omittag:t
  476. sgml-shorttag:t
  477. sgml-minimize-attributes:nil
  478. sgml-always-quote-attributes:t
  479. sgml-indent-step:1
  480. sgml-indent-data:t
  481. indent-tabs-mode:nil
  482. sgml-parent-document:nil
  483. sgml-default-dtd-file:"../../../../manual.ced"
  484. sgml-exposed-tags:nil
  485. sgml-local-catalogs:nil
  486. sgml-local-ecat-files:nil
  487. End:
  488. vim600: syn=xml fen fdm=syntax fdl=2 si
  489. vim: et tw=78 syn=sgml
  490. vi: ts=1 sw=1
  491. -->