Skip to content
Tutorials Center
My learning

Topics

Lesson 141 of 147 ยท Practice and Review

PHP Array Programs II: 15 More Classic Examples

15 more PHP array programs with output - second most frequent, missing numbers, closest value, sorting 0s 1s 2s, rotation check, triplets, median, leaderboard, XML and standard deviation.

PHP Programs: 50 Classic Examples covers the first wave of array exercises. This page continues with fifteen that interviewers and teachers like precisely because each has an obvious slow solution and a neat fast one: finding the second most frequent value, spotting missing numbers, checking whether a list is a rotated sorted list, computing a median of two sorted arrays, and so on. The last few are less puzzle and more daily work: binding an array to an SQL IN (...) clause, ranking a leaderboard, turning an array into XML, sorting objects by a field.

Every program is complete. Press Run to execute it on the PHP 8.5 command-line interpreter and edit the data to see how it reacts. All of them rely on the array tools from Array Functions, Sorting Arrays and Functional Array Functions; each explanation also says what to watch for.

Counting and finding

1. Second most frequent value

Count with array_count_values(), sort the counts in descending order while keeping the keys, and take the second key. Ties are broken by first appearance because PHP's sort is stable.

PHP 1. Second most frequent

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

array_count_values() only counts strings and integers; for floats or objects count with your own loop.

2. Find the missing numbers

Given numbers from 1 to n with some removed, build a lookup with array_flip() and walk the full range. That is O(n) instead of calling in_array() inside a loop, which is O(nยฒ).

PHP 2. Missing numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

3. The closest number

Walk the array once and keep the element with the smallest absolute difference to the target.

PHP 3. Closest number

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

4. Local maxima and minima

An element is a local maximum when it is larger than both neighbours. The first and last elements only have one neighbour, so they are compared with that one.

PHP 4. Local peaks and valleys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Sorted and rotated arrays

5. Sort an array of 0s, 1s and 2s

The Dutch national flag algorithm sorts in one pass with three pointers and no sorting function. low marks where the next 0 goes, high where the next 2 goes.

PHP 5. Sort 0s, 1s and 2s

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The swap uses array destructuring from Destructuring and Spread.

6. Is it a sorted and rotated array?

A sorted array that was rotated has at most one place where a number is bigger than the next one (counting the wrap-around from last to first).

PHP 6. Sorted and rotated?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

7. Median of two sorted arrays

The simple, readable approach merges the two sorted arrays and takes the middle. (The O(log n) version with binary search is a famous exercise, but the merge is what you would actually write.) For an even count the median is the average of the two middle values.

PHP 7. Median of two sorted arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Pairs and triplets

8. Pair with a given difference

Store every value in a set. For each x, check whether x + diff is in the set. That is O(n) with a hash lookup via isset().

PHP 8. Pair with a difference

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

9. Arithmetic progression triplets

A triplet a < b < c forms an arithmetic progression when b - a === c - b, i.e. a + c === 2 * b. For a sorted array of distinct numbers, fix the middle b and move two pointers outward.

PHP 9. AP triplets

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Statistics

10. Range sums, products and the mean

array_sum() and array_product() accept any array, so a range operation is array_slice() plus one of them. Remember that the slice length is end - start + 1 when both ends are inclusive.

PHP 10. Range sum, product and mean

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

11. Standard deviation

Population standard deviation is the square root of the mean of squared differences from the mean. For a sample divide by n - 1 instead of n.

PHP 11. Standard deviation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Practical arrays

12. Bind an array to an SQL IN() clause

IN (?, ?, ?) needs one placeholder per value. Build the placeholder list with str_repeat() and pass the values to execute(), so the query stays safe from injection. This runs against an in-memory SQLite database, as in PDO Basics.

PHP 12. IN() with a PDO array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

13. A leaderboard with ranks

Sort by score descending, then give equal scores the same rank ("1224" ranking: after a tie the next rank skips).

PHP 13. Leaderboard with ties

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Comparing arrays with <=> compares element by element, a compact way to sort by several keys. It is explained in Sorting Arrays.

14. Array to XML

Use SimpleXMLElement and recurse. Numeric keys cannot be element names, so they get a generic name. See XML for the whole toolbox.

PHP 14. Array to XML

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

addChild() does not escape the ampersand in its second argument, so htmlspecialchars() is required for text that may contain & or <.

15. Sort objects by a field

usort() with the spaceship operator sorts objects by any property. Chain comparisons by comparing arrays of properties.

PHP 15. Sort objects by a field

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is looking up values in a flipped array (isset on array_flip) faster than in_array() inside a loop?

    A loop with in_array() is O(n squared). A hash lookup through isset() makes the loop O(n).
  2. 2. How many "drops" (an element greater than its next element, wrapping around) can a sorted and rotated array have at most?

    A sorted array rotated once has a single place where the order breaks; a non-rotated sorted array has none.
  3. 3. What is the difference between population and sample standard deviation?

    Dividing by n - 1 corrects the bias when you only have a sample of the whole population.
  4. 4. Why must an empty array be handled before building an IN() clause?

    IN () is a syntax error in most databases, so return early or use a condition that is always false.

Summary

  • Count with array_count_values(), search with array_flip() plus isset() for O(1) lookups.
  • One pass with two or three pointers solves many "sorted" problems (Dutch flag, triplets).
  • A sorted array rotated once has at most one drop when you compare each element with the next, wrapping around.
  • Median and standard deviation need only sort(), array_sum() and sqrt().
  • Build IN (?, ?, ...) from array_fill() and implode(), and handle the empty case.
  • Sort by several keys by comparing arrays with <=> inside usort().

Next: PHP String Programs II