11 January 2016

Getting every other member of array in PHP. Examples of getting even or odd members of an array, using foreach loop and "modulo operation". The modulo operation (division by %) finds the remainder after division of one number by another.

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