w3resource

PHP Exercises: Count the number of two 5's are next to each other in an array of integers

PHP Basic Algorithm: Exercise-37 with Solution

Write a PHP program to count the number of two 5's are next to each other in an array of integers. Also count the situation where the second 5 is actually a 6.

Sample Solution:

PHP Code :

<?php
// Define a function that counts the occurrences of specific patterns in an array
function test($numbers)
{
    // Initialize a counter variable
    $ctr = 0;

    // Iterate through the array up to the second-to-last element
    for ($i = 0; $i < sizeof($numbers) - 1; $i++)
    {
        // Check if the current and next elements form a specific pattern
        if (($numbers[$i] == 5) && ($numbers[$i + 1] == 5) || ($numbers[$i + 1] == 6))
        {
            // Increment the counter if the pattern is found
            $ctr++;
        }
    }

    // Return the final count
    return $ctr;
}

// Test the function with different arrays
echo test([5, 5, 2])."\n";
echo test([5, 5, 2, 5, 5])."\n";
echo test([5, 6, 2, 9])."\n";
?>

Sample Output:

1
2
1

Visual Presentation:

PHP Basic Algorithm Exercises: Count the number of two 5's are next to each other in an array of integers

Flowchart:

Flowchart: Count the number of two 5's are next to each other in an array of integers.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to create a new string of the characters at indexes 0,1,4,5,8,9 ... from a given string.
Next: Write a PHP program to check if a triple is presents in an array of integers or not. If a value appears three times in a row in an array it is called a triple.

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.