w3resource

PHP Exercises: Check if a given array of integers contains a 3 or a 5


114. Contains 3 or 5 in Array Check

Write a PHP program to check if a given array of integers contains a 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)
 { 
    // Iterate through the elements of the array using a for loop
    for ($i = 0; $i < sizeof($nums); $i++)
    {
        // Check if the current element is not equal to 3 and not equal to 5, return false if true
        if ($nums[$i] != 3 && $nums[$i] != 5) return false;
    }

    // Return true if all elements are either 3 or 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(true)
bool(false)

Flowchart:

Flowchart: Check if a given array of integers contains a 3 or a 5.

For more Practice: Solve these Related Problems:

  • Write a PHP script to check if a given array contains either the number 3 or the number 5 and return a boolean accordingly.
  • Write a PHP function to scan through an array and output true if at least one element is equal to 3 or 5.
  • Write a PHP program to iterate over an array using a loop and check for the presence of the digits 3 or 5.
  • Write a PHP script to implement a combined condition that returns true if the array contains either a 3 or a 5 among its elements.

Go to:


PREV : Compare Count of 3's and 5's in Array.
NEXT : Array Contains No 3 or 5 Check.

PHP Code Editor:



Contribute your code and comments through Disqus.

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.