Foreach Loops - Range Operator

The range operator can be used in conjunction with #set and #foreach statements. Useful for its ability to produce an object array containing integers, the range operator has the following construction:

[n..m]

Both n and m must either be or produce integers. Whether m is greater than or less than n will not matter; in this case the range will simply count down. Examples showing the use of the range operator as provided below:

  1. First example:  
  2. #foreach( $foo in [1..5] )  
  3.       $foo  
  4. #end  
  5.   
  6. Second example:  
  7. #foreach( $bar in [2..-2] )  
  8.       $bar  
  9. #end  
  10.   
  11. Third example:  
  12. #set( $arr = [0..1] )  
  13. #foreach( $i in $arr )  
  14.       $i  
  15. #end  
  16.   
  17. Fourth example:  
  18. [1..3]  
  19.   
  20. ##Produces the following output:  
  21.   
  22. First example:  
  23. 1 2 3 4 5  
  24.   
  25. Second example:  
  26. 2 1 0 -1 -2  
  27.   
  28. Third example:  
  29. 0 1  
  30.   
  31. Fourth example:  
  32. [1..3]  

Note that the range operator only produces the array when used in conjunction with #set and #foreach directives, as demonstrated in the fourth example.

Web page designers concerned with making tables a standard size, but where some will not have enough data to fill the table, will find the range operator particularly useful.

comments powered by Disqus