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?

6
  • 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. Commented Jul 6, 2020 at 16:55
  • 1
    Isn't there 4 * 3 * 2 * 1 ways to write four elements? Commented Jul 6, 2020 at 16:55
  • what the logic behind this ? Commented Jul 6, 2020 at 16:55
  • 1
    Does this answer your question? PHP: How to get all possible combinations of 1D array? Commented Jul 6, 2020 at 17:01
  • Share your logic . check this combination also Commented Jul 6, 2020 at 17:06

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.