5

PHP Program to Count Digits of a Number

 9 months ago
source link: https://www.geeksforgeeks.org/php-program-to-count-digits-of-a-number/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

PHP Program to Count Digits of a Number

Discuss
Courses

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:

Using strlen() Function

The strlen() function returns the length of a given string. It takes a string as a parameter and returns it’s length. It calculates the length of the string including all the whitespaces and special characters.

Syntax:

strlen( $string );

Example:

<?php
$numStr1 = '110010';
$digitCount1 = strlen($numStr1);
echo "String Length: " . $digitCount1;
$number = 12345;
$numStr2 = (string)$number;
$digitCount2 = strlen($numStr2);
echo "\nString Length: " . $digitCount2;
?>
Output
String Length: 6
String Length: 5

Using while Loop

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
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;
?>
Output
String Length: 6
String Length: 5

Using str_split() Function

The str_split() function converts the given string into an array, and then use count() function to count total number of digits in given number.

Example:

<?php
function countDigits($number) {
$digits = str_split($number);
$digitCount = count($digits);
return $digitCount;
}
$numStr = '110010';
$digitCount1 = countDigits($numStr);
echo "String Length: " . $digitCount1;
$number = 12345;
$digitCount2 = countDigits((string)$number);
echo "\nString Length: " . $digitCount2;
?>
Output
String Length: 6
String Length: 5
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!
Last Updated : 12 Dec, 2023
Like Article
Save Article

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK