Find Number Combinations in PHP

Beginner
⏱️ 10 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Nested loops

What You’ll Learn

“Number combinations” in beginner exercises usually means nested-loop index patterns: every ordering of three values, then every unordered pair from a longer list. This tutorial covers permutations vs combinations, distinct-index rules, a live preview, worked PHP examples, edge cases, and complexity.

Permutations

Order matters

List every ordering of three fixed numbers (3! = 6 lines).

Combinations

Order ignored

List each unordered pair once with j > i.

Distinct Indices

i ≠ j ≠ k

Use each array slot once per printed triple.

4 Choose 2

Six pairs

Classic C(4, 2) listing from four numbers.

Live Preview

Three ints

Type three integers and see all six orderings.

O(n²) Pairs

Nested cost

Pair loops are quadratic; fixed size-3 perms are O(1).

Introduction

Number combination exercises usually ask you to systematically try index patterns with nested loops. First: every way to fill three slots from three values (permutations). Second: every way to pick two slots from four without repeating the same pair (combinations).

Think of three chairs and three people for Example 1: each seating arrangement is a different ordering. For Example 2 you only pick two people out of four and do not care who was “first,” so you force the first index to be smaller than the second.

Why it matters?

It trains nested loops, index discipline, and the vocabulary of permutation vs combination before heavier combinatorics or recursion.

Key Highlights

Order Matters?

Yes → permutation; no → combination.

Distinct Slots

i, j, k all unequal for three-of-three.

j Starts at i+1

Lists each unordered pair once.

Paper-Sized First

Trace small arrays before scaling up.

In short: use nested loops with the right index rules — distinct indices for orderings, j > i for unordered pairs — and print each valid selection.

📝 Problem & Approach

Store numbers in an array, then visit valid index tuples with nested for loops and print each result.

php
// [1, 2, 3] orderings -> 6 lines (permutations)
// [10, 20, 30, 40] pairs -> 6 lines (C(4, 2))

Inputs & Outputs

ItemTypeDescription
$arrarraySmall list of integers to rearrange or pair.
Printed outputtextOne line per valid ordering or pair.

Minimal workflow

Pseudocode
// All orderings of three array entries (indices 0..2)
for i in 0..2:
  for j in 0..2:
    for k in 0..2:
      if i, j, k all different:
        print arr[i], arr[j], arr[k]

// All unordered pairs from indices 0..n-1
for i in 0..n-2:
  for j in i+1 .. n-1:
    print arr[i], arr[j]

Method comparison

PatternIndex ruleCounts
Permutation (size 3)i, j, k all distinct3! = 6 when values differ
Unordered pairsj = i + 1 .. n-1C(n, 2)
Ordered pairsi != jn(n-1)

⚡ Quick Reference

GoalPattern
Distinct triple indicesif ($i !== $j && $j !== $k && $i !== $k)
Unordered pairfor ($j = $i + 1; $j < $n; $j++)
Ordered pairif ($i !== $j) inside double loop
Print a tripleecho $arr[$i] . " " . $arr[$j] . " " . $arr[$k] . "\n";
Count of 3-perms3! = 6 for three distinct values
Count of pairsC(n, 2) = n(n-1)/2

📋 Permutation vs Combination vs Ordered Pair

Same nested-loop toolbox — different index rules and meanings.

Permutation
order matters

Example 1 — all seatings of three values

Combination
j > i

Example 2 — each unordered pair once

Ordered pair
i != j

Example 3 — (a,b) and (b,a) both count

Interview tip
ask order?

Clarify before choosing the index rule

Context

When This Problem Shows Up

Reach for these nested-loop patterns when you must list selections systematically.

  1. Interview warm-ups

    Nested loops, index rules, and perm vs combo vocabulary.

  2. Before recursion

    See the pattern on paper before Heap’s algorithm.

  3. Pair generation

    All teams of two, all edges in a complete graph.

  4. Teaching nCr / nPr

    Visit each subset or ordering instead of only counting.

  5. Not for huge n alone

    Deep nesting explodes — cap demos and discuss asymptotics.

Key benefit: one visual nested-loop drill that separates “order matters” from “order does not.”

🔮 Live Preview

Enter three integers separated by commas (same as Example 1: 1, 2, 3). Shows all six orderings when indices are distinct.

Duplicate inputs can repeat the same-looking triple; the PHP program can be extended to skip duplicates if needed.

Live result
Press “List orderings”.

Examples Gallery

Three complete PHP programs — permutations of three numbers, unordered pairs from four, and ordered pairs. Click View Output to reveal sample console results.

📚 Getting Started

All orderings of three fixed values.

Example 1 — All Orderings of Three Numbers

Array [1, 2, 3]. These are permutations (order matters). Mathematicians reserve “combination” for selections where order does not matter.

php
<?php
$arr = [1, 2, 3];

echo "All orderings (permutations) of the three numbers:\n";

for ($i = 0; $i < 3; $i++) {
    for ($j = 0; $j < 3; $j++) {
        for ($k = 0; $k < 3; $k++) {
            if ($i !== $j && $j !== $k && $i !== $k) {
                echo $arr[$i] . " " . $arr[$j] . " " . $arr[$k] . "\n";
            }
        }
    }
}
?>

How It Works

The condition $i !== $j && $j !== $k && $i !== $k ensures each printed triple uses three different positions, so each value appears once per line. For three distinct numbers you always get 3! = 6 lines.

⚡ Combinations (Order Ignored)

Each unordered pair appears once — classic choose-2 listing.

Example 2 — All Unordered Pairs from Four Numbers

Values 10, 20, 30, 40. Each unordered pair appears once — C(4, 2) = 6 lines.

php
<?php
$arr = [10, 20, 30, 40];
$n = count($arr);

echo "All unordered pairs (choose 2 from $n):\n";

for ($i = 0; $i < $n; $i++) {
    for ($j = $i + 1; $j < $n; $j++) {
        echo $arr[$i] . " " . $arr[$j] . "\n";
    }
}
?>

How It Works

Starting $j at $i + 1 skips self-pairs and skips the reverse of each pair. That is the standard nested-loop shape for combinations of size 2.

⚙️ When Order Matters for Pairs

If (a, b) and (b, a) should both appear, drop the j > i rule.

Example 3 — All Ordered Pairs (i ≠ j)

Same four numbers, but both directions count — 4 × 3 = 12 lines.

php
<?php
$arr = [10, 20, 30, 40];
$n = count($arr);

echo "All ordered pairs (i != j):\n";

for ($i = 0; $i < $n; $i++) {
    for ($j = 0; $j < $n; $j++) {
        if ($i !== $j) {
            echo $arr[$i] . " " . $arr[$j] . "\n";
        }
    }
}
?>

How It Works

Compared with Example 2, you keep both 10 20 and 20 10. Ask the interviewer whether order matters before choosing j = i + 1 vs i !== $j.

🧠 How the Nested Loops Visit Selections

1

Store values

Put the numbers in an indexed array.

Setup
2

Choose the index rule

Distinct indices for perms; j > i for unordered pairs.

Rule
3

Print each hit

One echo per valid tuple of indices.

Output
=

List complete

Every valid ordering or pair has been printed.

🔎 Worked Walkthrough — Pairs from [10, 20, 30, 40]

Trace Example 2: outer $i, then $j from $i + 1.

$i$j valuesPrinted pairs
0 (10)1, 2, 310 20, 10 30, 10 40
1 (20)2, 320 30, 20 40
2 (30)330 40
3 (40)(none)

Total: 3 + 2 + 1 = 6 = C(4, 2).

Use Cases

Where permutation and combination nested loops show up beyond the prompt.

1. Interview Warm-Ups

Nested loops and clear index rules.

Example: print all pairs with j > i.

2. Teaching nCr / nPr

Visit each selection instead of only counting.

Example: C(4, 2) = 6 lines.

3. Pairwise Checks

Compare every unordered duo in a list.

Example: find equal pairs.

4. Before Recursion

Build intuition before recursive generators.

Example: Heap’s algorithm later.

5. Complexity Talk

State O(n²) for pairs, O(n³) for triples.

Example: interview asymptotics.

6. Vocabulary Clarity

Separate “combination lock” talk from math terms.

Example: order matters or not?

Pro Tip: ask “does order matter?” before writing the first nested loop.

Advantages

Why nested-loop listing works well for beginners and interviews.

  1. 1. Easy to Trace

    Dry-run small arrays on paper and match the printed lines.

  2. 2. Teaches Index Rules

    Distinct vs j > i is the whole skill in miniature.

  3. 3. No Recursion Required

    Beginners can finish without call stacks or backtracking.

  4. 4. Clear Complexity Story

    Fixed 3-perms are O(1); general pairs are O(n²).

Pro Tip: name the pattern aloud (“unordered pairs with j = i + 1”) before coding the loops.

Usage Tips

Small habits that keep combination listings interview-ready.

  1. 1. Clarify Order First

    Permutation vs combination changes the index rule.

  2. 2. Prefer j = i + 1

    Cleaner than a full double loop plus j > i checks.

  3. 3. Watch Duplicate Values

    Identical numbers can print identical-looking lines.

  4. 4. Count Expected Lines

    3! or C(n, 2) is a fast self-check.

  5. 5. Cap Demo Sizes

    Keep n small while learning; mention recursion for larger sets.

Pro Tip: dry-run C(4, 2) as 3+2+1 before coding — if your loop prints six lines, the bounds are almost certainly right.

Common Pitfalls

Mistakes that commonly break combination / permutation listings.

  1. 1. Mixing Up Order Rules

    Using j > i when the prompt wants both (a,b) and (b,a).

    → Ask whether order matters first.

  2. 2. Forgetting Distinct Indices

    Printing triples that reuse the same array slot.

    → Require i, j, k all different.

  3. 3. Off-by-One on Pair Loops

    Starting $j at $i includes self-pairs.

    → Start at $i + 1 for unordered pairs.

  4. 4. Ignoring Duplicate Values

    Identical numbers produce duplicate-looking output.

    → Filter or sort if uniqueness is required.

  5. 5. Scaling Nested Loops Blindly

    Using three nested loops for huge n without discussing cost.

    → State O(n³) and mention better generators for large sets.

Edge Cases

Handle these before calling the listing done.

Duplicates

Same value twice

Example 1 may print duplicate-looking triples; tighten logic if you need unique outputs only.

Small n

n < 2 for pairs

The inner loop never runs; no pairs to print — expected.

n = 2

Exactly one pair

Unordered listing prints a single line.

Empty

Empty array

Print nothing; guard if callers can pass empty input.

Negatives

Negative values

Index rules still work; values are just numbers.

Large n

Many elements

Output and time explode — discuss better algorithms.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • nPr. Ordered selections of r from n: n! / (n-r)! — Example 1 is 3P3 = 6.
  • nCr. Unordered selections: n! / (r!(n-r)!) — Example 2 is C(4, 2) = 6.
  • Identity. C(n, 2) = 1 + 2 + … + (n-1) — matches the walkthrough triangle of pairs.
  • Everyday language. A “combination lock” is closer to a permutation — order matters.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Dry-run 1,2,3

  • List all six permutations by hand
  • Match Example 1 output

2. C(5, 2)

  • Extend Example 2 to five numbers
  • Expect 10 unordered pairs

3. Ordered vs unordered

  • Compare Example 2 and Example 3 line counts
  • Explain why 6 vs 12

4. Duplicate values

  • Try permutations of [1, 1, 2]
  • Decide if you need unique printed lines

Notes

  • Orderings: distinct indices i, j, k give permutations of three entries.
  • Pairs: j > i lists each 2-combination once.
  • Vocabulary: permutation vs combination depends on whether order matters.
  • Bigger sets: nested loops do not scale — use recursion or libraries for large n.

Quick Takeaway: distinct indices for orderings, j = i + 1 for unordered pairs — and say whether order matters.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Three nested loops, size 3O(1) (fixed 27 iterations)O(1)
Unordered pairs from nO(n²)O(1)
Ordered pairs from nO(n²)O(1)

For general triples from n elements, expect O(n³) if you scan all index triples.

Wrap Up

🎉 Conclusion

Number-combination drills are nested loops with the right index rules: distinct slots for permutations, j > i for unordered pairs, and i != j when order matters. Master the vocabulary and the counts (3!, C(n, 2)) so you can explain either pattern in an interview.

Practice the three examples above, then continue to checking odd numbers.

Ask whether order matters, pick the matching index rule, and verify the line count against 3! or C(n, 2).

💡 Best Practices

✅ Do

  • Clarify permutation vs combination first
  • Use distinct indices for size-3 orderings
  • Start pair loops at $i + 1
  • Count expected lines (3! or C(n, 2))
  • State O(n²) for general pair scans

❌ Don’t

  • Reuse the same index in a “permutation”
  • Print both (a,b) and (b,a) for combinations
  • Ignore duplicate-value output surprises
  • Scale deep nesting without discussing cost
  • Confuse everyday “combination lock” with nCr

Key Takeaways

Knowledge Unlocked

Five things to remember about number combinations

List selections the interview-friendly way.

5
Core concepts
C 02

Combo

j > i pairs

Vocab
03

Indices

i, j, k distinct

Rule
! 04

Counts

3! / C(n,2)

Check
O 05

Cost

O(n²) pairs

Analysis

❓ Frequently Asked Questions

We show classic nested-loop patterns: (1) every way to order three given numbers — a permutation; (2) every way to pick two different numbers when order does not matter — pairs with j > i, which matches a 2-combination.
You need one loop index for each position in the triple. Requiring i, j, k all different makes sure you use each array slot once per line.
There are 3! = 6 permutations. If two numbers are equal, some lines can look the same — you can add checks to skip duplicates if needed.
That way each unordered pair appears once. Without it you would get both (a,b) and (b,a), which is the same pair for combinations.
Example 2 is the small case of choosing 2 from 4. The general nCr formula counts how many such subsets exist; the loops visit each subset explicitly.
Example 1 does O(1) work for fixed size 3. Example 2 does O(n²) for n elements; scanning all triples from n would be O(n³).
When (a,b) and (b,a) should both count — use i != j instead of j > i.
For many items, recursion or library routines are better. These examples teach the index rules on paper-sized inputs.

Did you Know? 🔊

In everyday language people say “combination lock,” but mathematically a combination ignores order while a permutation counts different orders as different. This page shows both ideas with small nested loops so you can see the pattern before heavier math.

Continue to Odd Number

Learn how to check whether a number is odd using the modulo operator in PHP.

Odd number tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful