phpsplithtml-selectdelimited

Submit more than one value from a single selected option


I have a dropdown to display price ranges for searching.

HTML for dropdown:

<select name="price">
    <option>All (-)</option>
    <option>Rs.400 to Rs.1,000 (3)</option>
    <option>Rs.1,000 to Rs.2,000 (6)</option>
    <option>Rs.2,000 to Rs.4,000 (1)</option>
    <option>Rs.4,000+ (1)</option>
</select>

Using this option values, now I need to separate first and second price from user selection. Eg. If someone select Rs.400 to Rs.1,000 (3), then I need to get 400 and 1,000.

Can anybody tell me how can I do this in php. I tired it with php explode. but I could not figure this out correctly.


Solution

  • Inspired by a previous answer. I'd suggest.

    HTML

    <select name="price">
        <option value="|">All (-)</option>
        <option value="400|1000">Rs.400 to Rs.1,000 (3)</option>
        <option value="1000|2000">Rs.1,000 to Rs.2,000 (6)</option>
        <option value="2000|4000">Rs.2,000 to Rs.4,000 (1)</option>
        <option value="4000|">Rs.4,000+ (1)</option>
    </select> 
    

    PHP

    <?php
    
    function get_numeric($val) { 
      if (is_numeric($val)) { 
        return $val + 0; 
      } 
      return false; 
    } 
    
    $price_selected = isset($_REQUEST['price']) && trim($_REQUEST['price'])!="" ? $_REQUEST['price'] : "|"; // sets a default value
    
    list($lower, $upper) = array_map('get_numeric',explode('|', $price_selected, 2));
    
    var_dump($lower); // false when there's no lower limit
    
    var_dump($upper); // false when there's no upper limit
    
    ?>