w3resource

PHP Exercises: Check a specified number is present in a given array of integers

PHP Basic Algorithm: Exercise-32 with Solution

Write a PHP program to check a specified number is present in a given array of integers.

Sample Solution:

PHP Code :

<?php
// Define a function that checks if a given number is present in an array of numbers
function test($nums, $n)
{
    // Use in_array function to check if the number is present in the array
    if (in_array($n, $nums)) {
        return true;
    }

    // Return false if the number is not found in the array
    return false;
}

// Test the function with different arrays and numbers
var_dump(test(array(1,2,9,3), 3));
var_dump(test(array(1,2,2,3), 2));
var_dump(test(array(1,2,2,3), 9));
?>

Sample Output:

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

Visual Presentation:

PHP Basic Algorithm Exercises: Check a specified number is present in a given array of integers.

Flowchart:

Flowchart: Check a specified number is present in a given array of integers.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to count a substring of length 2 appears in a given string and also as the last 2 characters of the string. Do not count the end substring.
Next: Write a PHP program to check if one of the first 4 elements in an array of integers is equal to a given element.

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.