w3resource

PHP Exercises: Check a given array of integers and return true if the given array contains two 5's next to each other, or two 5 separated by one element


117. Array Contains Two 5's Next to or Separated by One

Write a PHP program to check a given array of integers and return true if the given array contains two 5's next to each other, or two 5 separated by one element.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that takes an array of numbers as a parameter
function test($numbers)
 { 
    // Calculate the length of the array
    $len = sizeof($numbers);

    // Iterate through the elements of the array up to the second-to-last element
    for ($i = 0; $i < $len - 1; $i++)
    {
        // Check if there are consecutive occurrences of 5 and 5
        if ($numbers[$i] == 5 && $numbers[$i + 1] == 5) return true;

        // Check if there are non-consecutive occurrences of 5 and 5 with one element in between
        if ($i + 2 < $len && $numbers[$i] == 5 && $numbers[$i + 2] == 5) return true;
    }

    // Return false if there are no consecutive or non-consecutive occurrences of 5 and 5
    return false;
 }   

// Use 'var_dump' to print the result of calling 'test' with different arrays
var_dump(test([5, 5, 1, 5, 5]));
var_dump(test([1, 2, 3, 4]));
var_dump(test([3, 3, 5, 5, 5, 5]));
var_dump(test([1, 5, 5, 7, 8, 10]));
?>

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 two 5's next to each other, or two  5 separated by one element.

For more Practice: Solve these Related Problems:

  • Write a PHP script to check if an array contains two 5's either directly adjacent or separated by one element.
  • Write a PHP function to detect patterns where the number 5 occurs with at most one number between occurrences.
  • Write a PHP program to iterate through an array and use index comparisons to determine if two 5's are close enough according to the specified criteria.
  • Write a PHP script to implement conditional checks that return true if a valid pair of 5's is found with a gap of zero or one element.

Go to:


PREV : Contains Adjacent 3's or 5's Check.
NEXT : Array Contains 3 Followed Later by 5.

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.