# Count Number of digits in a number in PHP

Using iteration

```
<?php
//function to count number of digits
function countDigits($MyNum){
$MyNum = (int)$MyNum;
$count = 0;
while($MyNum != 0){
$MyNum = (int)($MyNum / 10);
$count++;
}
return $count;
}
$x = 123;
$y = 459709;
echo "$x contains: ".countDigits($x)." digits\n";
echo "$y contains: ".countDigits($y)." digits\n";
```

### Output

123 contains: 3 digits

459709 contains: 6 digits

459709 contains: 6 digits

Using Recursion

```
<?php
//function to count number of digits
function countDigits($MyNum){
$MyNum = (int)$MyNum;
if($MyNum != 0)
return 1 + countDigits($MyNum/10);
else
return 0;
}
$x = 564;
$y = 980620;
echo "$x contains: ".countDigits($x)." digits\n";
echo "$y contains: ".countDigits($y)." digits\n";
?>
```

### Output

564 contains: 3 digits

980620 contains: 6 digits

980620 contains: 6 digits