Q:

Write a PHP program to check a given array of integers and return true if the given array contains either 2 even or 2 odd values all next to each other

0

Write a PHP program to check a given array of integers and return true if the given array contains either 2 even or 2 odd values all next to each other.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

<?php
function test($numbers)
 { 
    $tot_odd = 0;
    $tot_even = 0;

    for ($i = 0; $i < sizeof($numbers); $i++)
          {
             if ($tot_odd < 2 && $tot_even < 2)
              {
                if ($numbers[$i] % 2 == 0)
                 {
                    $tot_even++;
                    $tot_odd = 0;
                  }
                else
                 {
                    $tot_odd++;
                    $tot_even = 0;
                 }
            }
          }
     return $tot_odd == 2 || $tot_even == 2;
 }   

var_dump(test([3, 5, 1, 3, 7]));
var_dump(test([1, 2, 3, 4]));
var_dump(test([3, 3, 5, 5, 5, 5]));
var_dump(test([2, 4, 5, 6]));

Sample Output:

bool(true)
bool(false)
bool(true)
bool(true)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now