11 January 2016

Using a loop to check the index of the element in the array is even or odd to get every other element. Examples of getting even or odd members of an array, using foreach loop and "modulo operation".In mathematics, the modulo operation is the remainder when one number is divided by another. It is denoted using the symbol % (percent sign) in many programming languages, including PHP.

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