w3resource

PHP Exercises: 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

PHP Basic Algorithm: Exercise-122 with Solution

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.

Sample Solution:

PHP Code :

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

    // Iterate through the elements of the array up to the specified length
    for ($i = 0; $i < $len; $i++)
    {
        // Check if the current element is not equal to the corresponding element from the end of the array
        if ($numbers[$i] != $numbers[$arra_size - $len + $i])
        {
            // Return false if the condition is met
            return false;
        }
    }

    // Return true if the specified length of elements from the beginning and end of the array are equal
    return true;
}   

// Use 'var_dump' to print the result of calling 'test' with different arrays and lengths
var_dump(test([3, 7, 5, 5, 3, 7], 2));
var_dump(test([3, 7, 5, 5, 3, 7], 3));
var_dump(test([3, 7, 5, 5, 3, 7, 5], 3));

Sample Output:

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

Flowchart:

Flowchart: 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.

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 every 5 that appears in the given array is next to another 5.
Next: Write a PHP program to check a given array of integers and return true if the array contains three increasing adjacent numbers.

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-122.php