w3resource

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


135. Check if Integer Contains Digit 2

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.

For more Practice: Solve these Related Problems:

  • Write a PHP script to determine if a positive integer contains the digit 2 by converting it to a string and searching.
  • Write a PHP function to scan each digit of an integer and return true if any digit equals 2.
  • Write a PHP program to use strpos() on a string representation of an integer to detect the presence of the digit 2.
  • Write a PHP script to implement a loop that checks each digit of an integer for the value 2 and outputs a boolean result.

Go to:


PREV : New Array from First n Strings.
NEXT : New Array from Odd Numbers with Given Length.

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.