How to generate all permutations of a string in PHP?
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
Generating all permutations of a string in PHP is a classic recursion exercise, but practical implementations need to handle duplicate characters, memory pressure, and runtime growth. The number of permutations grows factorially, so algorithm choice matters as input length increases. A clean implementation starts with correctness, then adds deduplication and iteration strategies.
Recursive Baseline for Unique Characters
If all characters are distinct, a recursive swap or prefix method is straightforward. The function below returns every permutation as a list.
This is easy to understand and test. It is a good baseline for interviews and small inputs.
Handle Duplicate Characters Correctly
If the input contains repeated characters, naive recursion returns duplicates. You can deduplicate after generation, but it wastes time and memory. Better approach is pruning duplicates during recursion.
This avoids repeated output while preserving lexicographic order.
Use a Generator for Memory Efficiency
Returning all permutations as one array can exhaust memory for larger inputs. A generator yields values one by one.
This pattern is useful when permutations feed a search pipeline and you can stop early after the first matching candidate.
Complexity and Practical Limits
For n unique characters, count is n!. Even 10! is already very large. Plan safeguards:
- reject inputs above a chosen threshold
- stream results with generators
- stop early if a downstream condition is satisfied
You can estimate expected count first:
Testing for Correctness
Add quick assertions:
- expected count for unique input
- no duplicates for repeated-character input
- deterministic ordering if required
Small tests catch most logic errors before performance tuning begins.
Common Pitfalls
- Generating all permutations into memory when streaming would suffice.
- Ignoring duplicate-character pruning and returning repeated strings.
- Forgetting factorial growth and allowing unbounded input length.
- Mixing multibyte text with byte-based indexing functions.
- Benchmarking on tiny strings and assuming behavior scales linearly.
Summary
- Start with recursive correctness, then optimize for duplicates and memory.
- Use sorted characters plus visited tracking to avoid duplicate output.
- Prefer generators when consumers process permutations incrementally.
- Add input-size guardrails because factorial growth is steep.
- Validate behavior with small deterministic tests before scaling.
Related reading
- How to generate all the permutations of a multiset?
- How to Generate Combinations of Elements of a ListT in .NET 4.0
- How to generate maximally unbalanced AVL trees
- How to generate n different colors for any natural number n?
- how to generate Narcissistic numbers faster?
- How to generate random graphs?
- How to generate random numbers biased towards one value in a range?
- How to generate Sudoku boards with unique solutions

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.