You are here

11 January 2016

Getting every other member of array in PHP. Examples of getting every other odd and even numbers.

Source code viewer
  1. // Even members of an array:
  2. $a = array(0,1,2,3,4,5,6);
  3. foreach ($a as $nr) {
  4. if (!($nr % 2)) {
  5. echo $nr . ',';
  6. }
  7. }
  8. // Output: 0,2,4,6,
  9.  
  10. // Odd members of an array:
  11. $a = array(0,1,2,3,4,5,6);
  12. foreach ($a as $nr) {
  13. if ($nr % 2) {
  14. echo $nr . ',';
  15. }
  16. }
  17. // Output: 1,3,5,
Programming Language: PHP