PHP Exercises: Check if a given array of integers contains no 3 or a 5
PHP Basic Algorithm: Exercise-115 with Solution
Write a PHP program to check if a given array of integers contains no 3 or a 5.
Sample Solution:
PHP Code :
<?php
// Define a function named 'test' that takes an array of numbers as a parameter
function test($nums)
{
// Initialize variables $three and $five with values of false
$three = false;
$five = false;
// Iterate through the elements of the array using a for loop
for ($i = 0; $i < sizeof($nums); $i++)
{
// Check if the current element is equal to 3, set $three to true if true
if ($nums[$i] == 3) {$three = true;}
// Check if the current element is equal to 5, set $five to true if true
if ($nums[$i] == 5) {$five = true;}
// Check if both $three and $five are true, return false if true
if ($three && $five) return false;
}
// Return true if there are no consecutive occurrences of both 3 and 5, otherwise return false
return true;
}
// Use 'var_dump' to print the result of calling 'test' with different arrays
var_dump(test([5, 5, 5, 5, 5]));
var_dump(test([3, 3, 3, 3]));
var_dump(test([3, 3, 3, 5, 5, 5]));
var_dump(test([1, 6, 8, 10]));
?>
Sample Output:
bool(true) bool(true) bool(false) bool(true)
Flowchart:
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a PHP program to check if a given array of integers contains a 3 or a 5.
Next: Write a PHP program to check if an array of integers contains a 3 next to a 3 or a 5 next to a 5 or both.
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-115.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics