1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Permutations

Discussion in 'PHP' started by newzone, Nov 23, 2009.

  1. #1
    I'am looking for a small script that will take two words from two different arrays and will make combinations of 2.

    Examples:

    first array:
    red, blue, green
    PHP:
    second array:
    cat, elephant, monkey
    PHP:
    the result should be like this:

    red cat
    red elephant
    red monkey
    blue cat
    blue elephant
    blue monkey
    green cat
    green elephant
    green monkey
    
    PHP:
    but not combinations like "cat monkey"
     
    newzone, Nov 23, 2009 IP
  2. mastermunj

    mastermunj Well-Known Member

    Messages:
    687
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    110
    #2
    following might help.. please make modifications according to your convenience..

    
    <?php
    	
    	$arr1 = array('red', 'blue', 'green');
    	$arr2 = array('cat', 'elephant', 'monkey');
    	
    	$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;
    	}
    	
    ?>
    
    PHP:
     
    mastermunj, Nov 23, 2009 IP
    newzone likes this.
  3. ColdMoon

    ColdMoon Peon

    Messages:
    26
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    $colors = array('red', 'blue', 'green');
    $animals = array('cat', 'elephant', 'monkey');
    
    foreach ($colors as $color) {
    	foreach ($animals as $animal) {
    		echo $color . " " . $animal . "<br />";
    	}
    }
    PHP:
    Can't test it but it should work as expected.
     
    ColdMoon, Nov 23, 2009 IP
    newzone likes this.
  4. newzone

    newzone Well-Known Member

    Messages:
    2,865
    Likes Received:
    52
    Best Answers:
    0
    Trophy Points:
    135
    Digital Goods:
    1
    #4
    Thanks, both work. :)
     
    newzone, Nov 23, 2009 IP