Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can put all word arrays into one array and use a <strong>recursive</strong> function like this:</p> <pre><code>function concat(array $array) { $current = array_shift($array); if(count($array) &gt; 0) { $results = array(); $temp = concat($array); foreach($current as $word) { foreach($temp as $value) { $results[] = $word . ' ' . $value; } } return $results; } else { return $current; } } $a = array(array('dog', 'cat'), array('food', 'tooth'), array('car', 'bike')); print_r(concat($a)); </code></pre> <p>Which returns:</p> <pre><code>Array ( [0] =&gt; dog food car [1] =&gt; dog food bike [2] =&gt; dog tooth car [3] =&gt; dog tooth bike [4] =&gt; cat food car [5] =&gt; cat food bike [6] =&gt; cat tooth car [7] =&gt; cat tooth bike ) </code></pre> <p>But I guess this behaves badly for large arrays as the output array will be very big.</p> <hr> <p>To get around this, you can output the combinations directly, using a similar approach:</p> <pre><code>function concat(array $array, $concat = '') { $current = array_shift($array); $current_strings = array(); foreach($current as $word) { $current_strings[] = $concat . ' ' . $word; } if(count($array) &gt; 0) { foreach($current_strings as $string) { concat($array, $string); } } else { foreach($current_strings as $string) { echo $string . PHP_EOL; } } } concat(array(array('dog', 'cat'), array('food', 'tooth'), array('car', 'bike'))); </code></pre> <p>Which gives:</p> <pre><code>dog food car dog food bike dog tooth car dog tooth bike cat food car cat food bike cat tooth car cat tooth bike </code></pre> <p>With this approach it is also easy to get the "sub-concatinations". Just insert <code>echo $string . PHP_EOL;</code> before <code>concat($array, $string);</code> and the output is:</p> <pre><code> dog dog food dog food car dog food bike dog tooth dog tooth car dog tooth bike cat cat food cat food car cat food bike cat tooth cat tooth car cat tooth bike </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload