1

I have this array:

array('Volvo', 'BMW', 'Toyota', 'Kijang');

And I want results like this

"Volvo","BMW","Toyota","Kijang"
"BMW","Volvo","Toyota","Kijang"
"Toyota","Volvo","BMW","Kijang"
"Kijang","Toyota","Volvo","BMW"

and here's my code :

$products = array('Volvo', 'BMW', 'Toyota', 'Kijang');

$rows = count($products);  

for ($i = 0; $i < $rows; $i++) {

    echo $products[$i] . '<br>';
}

but, unfortunately I missed 3 results :

"BMW","Volvo","Toyota","Kijang"
"Toyota","Volvo","BMW","Kijang"
"Kijang","Toyota","Volvo","BMW"

how to get that missed combination and perfectly works for different array length?

  • 1
    What are you trying to achieve? I'm not seeing how you determined the "results you want", bearing in mind there are 24 permutations of 4 items. – Niet the Dark Absol Jul 06 '20 at 16:55
  • 1
    Isn't there `4 * 3 * 2 * 1` ways to write four elements? – Progrock Jul 06 '20 at 16:55
  • what the logic behind this ? – Niklesh Raut Jul 06 '20 at 16:55
  • 1
    Does this answer your question? [PHP: How to get all possible combinations of 1D array?](https://stackoverflow.com/questions/10834393/php-how-to-get-all-possible-combinations-of-1d-array) – hanshenrik Jul 06 '20 at 17:01
  • Share your logic . [check this combination also](http://sandbox.onlinephpfunctions.com/code/c67501e8703e17b668c7b1a371a55d7164e53ae6) – Niklesh Raut Jul 06 '20 at 17:06
  • That code is definitely not going to produce three lines of 4 elements like you said it does. What are you trying to do here? Why just those 4 lines/permutations? This is not at all clear. – JNevill Jul 06 '20 at 17:08

2 Answers2

1

You can achieve this in this way as well.

<?php

   $products = array('Volvo', 'BMW', 'Toyota', 'Kijang');
     for($i=0;$i<count($products);$i++){
        echo implode(", ",$products);  
        echo "<br>";
        array_push($products, array_shift($products));
     }

?>

This will give you the following result:

Volvo, BMW, Toyota, Kijang
BMW, Toyota, Kijang, Volvo
Toyota, Kijang, Volvo, BMW
Kijang, Volvo, BMW, Toyota

You can run the code in here.Hope this will help you.

Hirumina
  • 738
  • 1
  • 9
  • 23
0

You can achive it in this way

<?php

$products = array('Volvo', 'BMW', 'Toyota', 'Kijang');

foreach($products as $product){
    echo "'".$product."', ";
    foreach($products as $otherProduct){
        if($otherProduct == $product){
            // Skip the element
            continue;
        }
        echo "'".$otherProduct."', ";
    }
    echo "<br>";
}

You need to loop twice to get the result.

mail2bapi
  • 1,547
  • 1
  • 12
  • 18