PHP Exercises: Check a given array of integers and return true if the array contains three increasing adjacent numbers
PHP Basic Algorithm: Exercise-123 with Solution
Write a PHP program to check a given array of integers and return true if the array contains three increasing adjacent numbers.
Sample Solution:
PHP Code :
<?php
// Define a function named 'test' that takes an array of numbers as a parameter
function test($numbers)
{
// Iterate through the elements of the array using a for loop
for ($i = 0; $i <= sizeof($numbers) - 3; $i++)
{
// Check if the current element is equal to the next element minus 1
// and if the current element is equal to the element after the next element minus 2
if ($numbers[$i] == $numbers[$i + 1] - 1 && $numbers[$i] == $numbers[$i + 2] - 2)
{
// Return true if the condition is met
return true;
}
}
// Return false if the condition is not met for any set of three consecutive elements
return false;
}
// Use 'var_dump' to print the result of calling 'test' with different arrays
var_dump(test([1, 2, 3, 5, 3, 7]));
var_dump(test([3, 7, 5, 5, 3, 7]));
var_dump(test([3, 7, 5, 5, 6, 7, 5]));
?>
Sample Output:
bool(true) bool(false) bool(true)
Flowchart:
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 specified number of same elements appears at the start and end of the given array.
Next: Write a PHP program to shift an element in left direction and return a new array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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-123.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics