Combine array values into a string


// Testing variable to check conditions.
$check = false;

$colors = array('red', 'white', 'green');
$sizes = array('small', 'medium', 'large');
$additionals = array('print', 'no print');
$combinations = array();

foreach($colors as $color) {
  foreach($sizes as $size) {
    // Add third level depending on the $check variable.
    if($check === true) {	
  	  foreach($additionals as $additional) {
	    $combinations[] = $color . '-' . $size . '-' . $additional;
	  }
	} else {
	  $combinations[] = $color . '-' . $size;	
	}
  }
}

print_r($combinations);

This returns:

Array ( [0] => red-small [1] => red-medium [2] => red-large [3] => white-small [4] => white-medium [5] => white-large [6] => green-small [7] => green-medium [8] => green-large )


// Testing variable to check conditions.
$check = true;

$colors = array('red', 'white', 'green');
$sizes = array('small', 'medium', 'large');
$additionals = array('print', 'no print');
$combinations = array();

foreach($colors as $color) {
  foreach($sizes as $size) {
    if($check === true) {	
  	  foreach($additionals as $additional) {
	    $combinations[] = $color . '-' . $size . '-' . $additional;
	  }
	} else {
	  $combinations[] = $color . '-' . $size;	
	}
  }
}

print_r($combinations);

This returns:

Array ( [0] => red-small-print [1] => red-small-no print [2] => red-medium-print [3] => red-medium-no print [4] => red-large-print [5] => red-large-no print [6] => white-small-print [7] => white-small-no print [8] => white-medium-print [9] => white-medium-no print [10] => white-large-print [11] => white-large-no print [12] => green-small-print [13] => green-small-no print [14] => green-medium-print [15] => green-medium-no print [16] => green-large-print [17] => green-large-no print )

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.