phparraysformsconditional-operatorcontrol-structure

Simplifying a nested If...Else statement; flexible array


So first off, here is the code:

  $greens = $_REQUEST['greens'];
  $squash = $_REQUEST['squash'];
  $tomatoes = $_REQUEST['tomatoes'];

  $single = $greens xor $squash xor $tomatoes;


  if (isset($greens,$squash,$tomatoes)) {

    $array = [$greens,$squash,$tomatoes];
    $product = implode(', ',$array);

  } else if (isset($greens,$squash)) {

    $array = [$greens,$squash];
    $product = implode(', ',$array);

  } else if (isset($greens,$tomatoes)) {

    $array = [$greens,$tomatoes];
    $product = implode(', ',$array);

  } else if (isset($squash,$tomatoes)) {

    $array = [$squash,$tomatoes];
    $product = implode(', ',$array);

  } else if (isset($single)) {

    $product = $single;

  } else {

    $product = $_REQUEST['vendor_product'];

  }

This is part of a php file to submit a vendor registration form. If the vendor selects 'produce' as their type of product, a set of checkbox options appears, and need to select at least one option. Depending on the set of options, the values selected would be collectively submitted into the database in one field. Examples of how they would be viewed in the database are: 'Greens, Squash & Zucchini', 'Greens, Squash & Zucchini, Tomatoes' and 'Greens', etc. where ', ' is inserted if more than one option is selected.

The code above works, but would like to know if there is a way to simplify this, as I will most likely be adding more options for the user to select from. Also, even though there are multiple true results for each condition, can the ternary operator still be used? I am still rather new to understanding that operator.


Solution

  • $names = ['greens', 'squash', 'tomatoes'];
    
    $array = [];
    foreach ($names as $name) {
        if (isset($_REQUEST[$name])) {
            $array[] = $_REQUEST[$name];
        }
    }
    
    $product = implode(', ',$array);
    
    if (count($array) == 0) {
        $product = $_REQUEST['vendor_product'];
    }