Results 1 to 4 of 4

Thread: Permutations help in php

  1. #1
    Join Date
    Nov 2009
    Posts
    356

    Permutations help in php

    Hi
    Actually I was trying a small script that will take two words from two different arrays, then I would like to combine both the arrays.
    My first array elements would be some thing like this
    Code:
    r, b, g
    My second array elements would e some thing like this 3
    Code:
    c, e, m
    The result I expect is
    Code:
    r c
    r e
    r m
    b c
    b e
    b m
    g c
    g e
    g m

  2. #2
    Join Date
    May 2008
    Posts
    2,389

    Re: Permutations help in php

    Hello
    You would like to try this code. If I am not wrong this will work as you are expecting. Try it.
    Code:
    <?php
       
        $arr1 = array('r', 'b', 'g');
        $arr2 = array('c', 'e', 'm');
        $arr_perm = get_permutations($arr1, $arr2);
        print_r($arr_perm); 
        function get_permutations($array1, $array2)
        {
            $result = '';
            foreach($array1 as $elem1)
            {
                foreach($array2 as $elem2)
                {
                    $result[] = $elem1 . ' ' . $elem2;
                }
            }
            return $result;
        }
    ?>

  3. #3
    Join Date
    Oct 2005
    Posts
    2,393

    Re: Permutations help in php

    Hello
    The above example is correct. This can be alternatively done in this way also. Just try to add your knowledge.
    Code:
    $colors = array('red', 'b', 'g');
    $animals = array('c', 'e', 'm');
    
    foreach ($colors as $color) {
        foreach ($animals as $animal) {
            echo $color . " " . $animal . "<br />";
        }
    }
    Want any more help, then do post back.

  4. #4
    Join Date
    Nov 2009
    Posts
    356

    Re: Permutations help in php

    Hi
    Thanks for your help and your code. Both the codes are working correctly. Thanks again for the simple example which are easy to understand.

Similar Threads

  1. Code for Permutations
    By Wappinger in forum Software Development
    Replies: 4
    Last Post: 29-12-2010, 08:31 AM
  2. How to perform permutations in c++
    By Linoo in forum Software Development
    Replies: 4
    Last Post: 09-02-2010, 07:37 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Page generated in 1,750,345,035.54523 seconds with 16 queries