w3resource

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

PHP Basic Algorithm: Exercise-121 with Solution

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.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to check a given array of integers and return true if the value 5 appears 5 times and there are no 5 next to each other.
Next: Write a PHP program to check a given array of integers and return true if the specified number of same elements appears at the start and end of the given array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/php-exercises/basic-algorithm/php-basic-algorithm-exercise-121.php