# Robson » Little Red Book » Smallest and largest

## Chapter 3 - Question 6

Design a program to process a seqeunce of non-negative integers, terminated by a single negative value and output the smallest and largest value in the sequence.

### Solution 1

Even though this problem is in the loops section, it doesn't need a loop to work out the smallest and largest values because PHP has some excellent array functions.

`<?`
`    // generate a random number of random numbers`
`    for (\$n = 0; \$n < mt_rand(5, 20); \$n++)`
`        \$sequence[] = mt_rand(1, 50);`
`        `
`    // add the terminator`
`    \$sequence[] = -1;    `
`    `
`    // show the sequence`
`    echo 'Sequence: ' . implode(', ', \$sequence) . '<br/>';`
`    `
`    // sort the sequence of numbers`
`    sort(\$sequence);`
`    `
`    // show the smallest and largest`
`    echo 'Smallest: ' . \$sequence . '<br/>Largest: ' . array_pop(\$sequence);        `
`?>`

Which produces:

Sequence: 5, 36, 49, 29, 28, 40, 39, 13, 37, -1
Smallest: 5
Largest: 49

## Log

• May 1, 2005 - Added solution 1.
© 2004-20 robson | cc unless stated