w3resource

PHP Exercises: Check a positive integer and return true if it contains a number 2

PHP Basic Algorithm: Exercise-135 with Solution

Write a PHP program to check a positive integer and return true if it contains a number 2.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that takes an integer 'n'
function test($n)
{ 
    // Use a while loop to iterate as long as 'n' is greater than 0
    while ($n > 0)
    {
        // Check if the last digit of 'n' is equal to 2
        if ($n % 10 == 2)
        {
            // If true, return true, indicating the presence of digit 2
            return true;
        }

        // Remove the last digit from 'n' by dividing it by 10
        $n /= 10;
    }

    // If the loop completes without finding digit 2, return false
    return false;
}

// Use var_dump to display the result of the 'test' function for different inputs
var_dump(test(123));
var_dump(test(13));
var_dump(test(222));
?>

Sample Output:

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

Flowchart:

Flowchart: Check a positive integer and return true if it contains a number 2.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to create a new array using the first n strings from a given array of strings. (n>=1 and <=length of the array).
Next: Write a PHP program to create a new array of given length using the odd numbers from a given array of positive 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.