Cycle or zebra between values


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. function cycle(/*$val1, $val2, $valN*/) {
  2. static $counter = 0;
  3. $values = func_get_args();
  4. $length = count($values);
  5. if ($length == 0) {
  6. $counter = 0;
  7. return null;
  8. }
  9. return $values[$counter++ % $length];
  10. }
  11.  
  12. // example usage
  13. $i = 0;
  14. while ($i++ < 5) {
  15. echo cycle('odd','even') . '<br>';
  16. }
  17.  
  18. cycle(); // reset
  19.  
  20. $i = 0;
  21. while ($i++ < 6) {
  22. echo cycle('a','b','c','d') . '<br>';
  23. }
  24.  
  25. /*
  26. output =>
  27.  
  28. odd
  29. even
  30. odd
  31. even
  32. odd
  33. a
  34. b
  35. c
  36. d
  37. a
  38. b
  39. */

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.