PHP Exercises: Check a given array of integers and return true if every 5 that appears in the given array is next to another 5
121. Check Every 5 is Paired with Another
Write a PHP program to check a given array of integers and return true if every 5 that appears in the given array is next to another 5.
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
$arr_len = sizeof($numbers);
// Initialize a variable $flag with a value of true
$flag = true;
// Iterate through the elements of the array using a for loop
for ($i = 0; $i < $arr_len; $i++) { // Check if the current element is 5 if ($numbers[$i] == 5) { // Check if there is a consecutive 5 before or after the current element if (($i> 0 && $numbers[$i - 1] == 5) || ($i < $arr_len - 1 && $numbers[$i + 1] == 5)) $flag = true; // Check if the current element is the last element in the array else if ($i == $arr_len - 1) $flag = false; else return false; } } // Return the value of $flag after iterating through the array return $flag; } // Use 'var_dump' to print the result of calling 'test' with different arrays var_dump(test([3, 5, 5, 3, 7])); var_dump(test([3, 5, 5, 4, 1, 5, 7])); var_dump(test([3, 5, 5, 5, 5, 5])); var_dump(test([2, 4, 5, 5, 6, 7, 5])); ?>
Sample Output:
bool(true) bool(false) bool(true) bool(false)
Flowchart:
Flowchart: Check a given array of integers and return true if every 5 that appears in the given array is next to another 5.For more Practice: Solve these Related Problems:
- Write a PHP script to verify that in a given array every occurrence of 5 has at least one adjacent 5.
- Write a PHP function to iterate through an array and return true if each 5 is immediately next to another 5.
- Write a PHP program to check pairs of elements in an array such that if an element equals 5 it is adjacent to another 5.
- Write a PHP script to use flag variables to validate that every 5 in the array is coupled with at least one neighboring 5.
Go to:
PREV : Check for Five Occurrences of 5 Without Neighbors.
NEXT : Same Number of Elements at Start and End.
PHP Code Editor:
Contribute your code and comments through Disqus.