Number of occurrences of 2 as a digit in numbers from 0 to n | Counts the number of '2' digits in a single number ; Counts the number of '2' digits between 0 and n ; Initialize result ; Count 2 's in every number  from 2 to n ; Driver Code
< ? php function number0f2s ( $ n ) { $ count = 0 ; while ( $ n > 0 ) { if ( $ n % 10 == 2 ) $ count ++ ; $ n = $ n / 10 ; } return $ count ; } function numberOf2sinRange ( $ n ) { $ count = 0 ; for ( $ i = 2 ; $ i <= $ n ; $ i ++ ) $ count += number0f2s ( $ i ) ; return $ count ; } echo ( numberOf2sinRange ( 22 ) ) ; echo " STRNEWLINE " ; echo numberOf2sinRange ( 100 ) ; ? >