w3resource

PHP Exercises: 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


119. Check for Two Consecutive Even or Odd Values

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.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that takes an array of numbers as a parameter
function test($numbers)
 { 
    // Initialize variables $tot_odd and $tot_even with values of 0
    $tot_odd = 0;
    $tot_even = 0;

    // Iterate through the elements of the array using a for loop
    for ($i = 0; $i < sizeof($numbers); $i++)
    {
        // Check if both $tot_odd and $tot_even are less than 2
        if ($tot_odd < 2 && $tot_even < 2)
        {
            // Check if the current element is even
            if ($numbers[$i] % 2 == 0)
            {
                // Increment $tot_even and reset $tot_odd if the element is even
                $tot_even++;
                $tot_odd = 0;
            }
            else
            {
                // Increment $tot_odd and reset $tot_even if the element is odd
                $tot_odd++;
                $tot_even = 0;
            }
        }
    }

    // Return true if there are two consecutive even or odd numbers, otherwise false
    return $tot_odd == 2 || $tot_even == 2;
 }   

// Use 'var_dump' to print the result of calling 'test' with different arrays
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)

Flowchart:

Flowchart: 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.

For more Practice: Solve these Related Problems:

  • Write a PHP script to determine if an array contains two adjacent even numbers or two adjacent odd numbers.
  • Write a PHP function to iterate through an array and return true if a pair of consecutive elements share evenness or oddness.
  • Write a PHP program to check adjacent pairs in an array for parity and output true if any pair matches.
  • Write a PHP script to use modulus operations to compare adjacent elements and verify if there are at least two evens or two odds in a row.

Go to:


PREV : Array Contains 3 Followed Later by 5.
NEXT : Check for Five Occurrences of 5 Without Neighbors.

PHP Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.