w3resource

PHP Exercises: Check if a given array of integers contains 5 next to a 5 somewhere

PHP Basic Algorithm: Exercise-110 with Solution

Write a PHP program to check if a given array of integers contains 5 next to a 5 somewhere.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that takes an array of numbers as a parameter
function test($nums)
 { 
    // Iterate through the elements of the array up to the second-to-last element
    for ($i = 0; $i < sizeof($nums) - 1; $i++)
    {
        // Check if the current element is 5 and is equal to the next element
        if ($nums[$i] == 5 && $nums[$i] == $nums[$i + 1]) return true;
    }

    // Return false if there are no consecutive elements equal to 5
    return false;
 }   

// Use 'var_dump' to print the result of calling 'test' with different arrays
var_dump(test([1, 5, 6, 9, 10, 17]));
var_dump(test([1, 5, 5, 9, 10, 17]));
var_dump(test([1, 5, 5, 9, 10, 17, 5, 5]));
?>

Sample Output:

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

Flowchart:

Flowchart: Check if a given array of integers contains 5 next to a 5 somewhere.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to compute the sum of the numbers in a given array except those numbers starting with 5 followed by atleast one 6. Return 0 if the given array has no integer.
Next: Write a PHP program to check whether a given array of integers contains 5's and 7's

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://w3resource.com/php-exercises/basic-algorithm/php-basic-algorithm-exercise-110.php