Answer the question
In order to leave comments, you need to log in
How can I change this function so that no more than X elements are displayed in one pass?
I was looking for a suitable solution for a long time (I needed to get all possible options for iterating a string array), I found a working option - stackoverflow.com/questions/10834393/php-how-to-ge...
The problem is that the function provides all possible options. I don’t understand how it needs to be changed so that the number of array elements in one answer does not exceed the specified number.
For example, in his example he has the line "Alpha Beta Gamma Sigma" - if I set the number 3 as a limiter, then it should not be in the result of the function, because it is the result of combining 4 elements, which is more than three. Can you please tell me how to correct the code?
Answer the question
In order to leave comments, you need to log in
As part of that program - something like this:
$array = array('Alpha', 'Beta', 'Gamma', 'Sigma');
function depth_picker($arr, $temp_string, &$collect, $len=0) {
$max = 3;
if ($len > $max) {
return;
}
if ($temp_string != "")
$collect []= $temp_string;
for ($i=0; $i<sizeof($arr);$i++) {
$arrcopy = $arr;
$elem = array_splice($arrcopy, $i, 1); // removes and returns the i'th element
if (sizeof($arrcopy) > 0) {
depth_picker($arrcopy, $temp_string ." " . $elem[0], $collect, $len+1);
} elseif ($len < $max) {
$collect []= $temp_string. " " . $elem[0];
}
}
}
$collect = array();
depth_picker($array, "", $collect);
print_r($collect);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question