# Robson » Little Red Book » Tallying

## Chapter 5 - Question 7

A program is required to process an input stream of single digit numbers and count the number of times each occurs.

The number of inputs will usually be in excess of fifty digits and will be terminated by a value of -1.

Each digit may be seperated from the rest by spaces and the input may occupy more than one line.

### Solution 1

`<?`
`    // some random numbers on multiple lines`
`    // any amount of numbers can be handled`
`    \$numbers = "5 7 9 4 2 5 4 4 7 2 9 0 7 `
`                5 9 3 1 2 6 7 8 9 4 2 1 8`
`                7 2 3 9 1 5 6 3 9 1 2 2 5`
`                4 0 3 2 1 8 7 5 9 1 6 3 2 -1";`
`    `
`    // get everything before the terminator value`
`    \$numbers = substr(\$numbers, 0, strrpos(\$numbers, '-1')-1);`
` `
`    // loop through possible values`
`    for (\$n = 0; \$n < 10; \$n++)`
`        // echo out the number of times that number appears`
`        echo \$n . ' = ' . substr_count(\$numbers, \$n) . '<br/>';`
`?>`

Which produces:

0 = 2
1 = 6
2 = 9
3 = 5
4 = 5
5 = 6
6 = 3
7 = 6
8 = 3
9 = 7

## Log

• March 28, 2005 - Added solution 1.
© 2004-19 robson | cc unless stated