

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Generate all combinations of a specific size from a single set in PHP
To generate all combinations of a specific size from a single set, the code is as follows −
Example
function sampling($chars, $size, $combinations = array()) { # in case of first iteration, the first set of combinations is the same as the set of characters if (empty($combinations)) { $combinations = $chars; } # size 1 indicates we are done if ($size == 1) { return $combinations; } # initialise array to put new values into it $new_combinations = array(); # loop through the existing combinations and character set to create strings foreach ($combinations as $combination) { foreach ($chars as $char) { $new_combinations[] = $combination . $char; } } # call the same function again for the next iteration as well return sampling($chars, $size - 1, $new_combinations); } $chars = array('a', 'b', 'c'); $output = sampling($chars, 2); var_dump($output);
Output
This will produce the following output −
array(9) { [0]=> string(2) "aa" [1]=> string(2) "ab" [2]=> string(2) "ac" [3]=> string(2) "ba" [4]=> string(2) "bb" [5]=> string(2) "bc" [6]=> string(2) "ca" [7]=> string(2) "cb" [8]=> string(2) "cc" }
The first iteration indicates the same set of characters to be displayed. If the size is 1, then the combination is displayed. An array is initialized as ‘new_combinations’ and it is looped through using the ‘forloop’ and every character in that string is concatenated with every other character. The function ‘sampling’ is called with the parameters (string, the size of the string and the array).
- Related Questions & Answers
- Generate all combinations of supplied words in JavaScript
- Generate all permutation of a set in Python?
- C++ Program to Generate All Possible Combinations of a Given List of Numbers
- C++ Program to Generate All Possible Combinations Out of a,b,c,d,e
- Print all possible combinations of r elements in a given array of size n in C++
- Print all subsets of given size of a set in C++
- Python – All combinations of a Dictionary List
- Python program to get all pairwise combinations from a list
- Python program to get all subsets of a given size of a set
- Python Pandas - Set only a single new specific level in a MultiIndex
- Get only a single value from a specific MySQL row?
- Python program to get all subsets of given size of a set
- How to generate a probability density distribution from a set of observations in R?
- How to set a single pixel using imagesetpixel() function in PHP?
- JavaScript function that generates all possible combinations of a string
Advertisements