w3resource

PHP Exercises: Check whether a given array of integers contains 5's and 7's

PHP Basic Algorithm: Exercise-111 with Solution

Write a PHP program to check whether a given array of integers contains 5's and 7's.

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 using a for loop
    for ($i = 0; $i < sizeof($nums); $i++)
    {
        // Check if the current element is equal to 5 or 7
        if ($nums[$i] == 5 || $nums[$i] == 7) return true;
    }

    // Return false if there are no elements equal to 5 or 7
    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, 4, 7, 9, 10, 17]));
var_dump(test([1, 1, 2, 9, 10, 17]));

Sample Output:

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

Flowchart:

Flowchart: Check whether a given array of integers contains 5's and 7's.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to check if a given array of integers contains 5 next to a 5 somewhere.
Next: Write a PHP program to check if the sum of all 5' in the array exactly 15 in a given array of integers.

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.