Open In App

PHP Program to Print All Digits of a Given Number

Last Updated : 24 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a number, the task is to print all digits of the given number in PHP. There are various methods to print all digits of the given number, we will cover each approach with explanations and examples.

Approach 1: Print All Digits of a Number using String Conversion

One simple approach to print all digits of a given number is to convert the number to a string and then iterate over each character (digit) in the string.

PHP
<?php

function printDigits($number) {
    $digits = str_split((string)$number);
    foreach ($digits as $digit) {
        echo $digit . " ";
    }
}

// Driver Code
$num = 12345;
printDigits($num);


?>

Output
1 2 3 4 5 

Approach 2: Print All Digits of a Number using Modulus Operator (%)

Another approach is to repeatedly divide the number by 10 and print the remainder (which is the last digit). Repeat this process until the number becomes 0.

PHP
<?php

function printDigits($number) {
    while ($number > 0) {
        $digit = $number % 10;
        echo $digit . " ";
        $number = (int)($number / 10);
    }
}

// Driver Code
$num = 12345;
printDigits($num);

?>

Output
5 4 3 2 1 

Approach 3: Print All Digits of a Number using Recursion

You can also use recursion to print digits of a number. The base case is when the number becomes 0. In this case, we repeatedly divide number and print the remainder.

PHP
<?php

function printDigits($number) {
    if ($number > 0) {
        printDigits((int)($number / 10));
        echo $number % 10 . " ";
    }
}

// Driver Code
$num = 12345;
printDigits($num);

?>

Output
1 2 3 4 5 

Approach 4: Print All Digits of a Number using Array and Loop

You can convert the number to an array of digits using str_split() and then iterate over the array to print each digit.

PHP
<?php

function printDigits($number) {
    $digits = str_split((string)$number);
    foreach ($digits as $digit) {
        echo $digit . " ";
    }
}

// Driver Code
$num = 12345;
printDigits($num);

?>

Output
1 2 3 4 5 

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads