How to use while Loop In PHP
In this section, we use while loop to count the digits of a Number. First, we declare a counter variable and initialize with 0. Then check the given number is not equal to zero, then divide the number by 10, and increase the counter variable by 1. At last, return the counter variable that display the total digits of a number.
PHP
<?php function countDigits( $number ) { $digitCount = 0; while ( $number != 0) { $number = (int)( $number / 10); $digitCount ++; } return $digitCount ; } $numStr = '110010' ; $digitCount1 = countDigits( $numStr ); echo "String Length: " . $digitCount1 ; $number = 12345; $digitCount2 = countDigits( $number ); echo "\nString Length: " . $digitCount2 ; ?> |
String Length: 6 String Length: 5
PHP Program to Count Digits of a Number
In this article, we will see how to count the digits of a number in PHP. There are three methods to count digits of a number, these are:
Table of Content
- Using strlen() Function
- Using while Loop
- Using str_split() Function