0

I'm collecting data from a form into a session, on another form, I use a few variables to feed a SELECT option, which works as I want. as shown here

<select class="select2_category form-control" data-placeholder="Choose a Category" tabindex="1" id="householder" name="householder">
    <option value=""></option>
    <option value="A"><?php echo $_SESSION["name1"];?></option>
    <option value="B"><?php echo $_SESSION["name2"];?></option>
    <option value="C"><?php echo $_SESSION["name3"];?></option>
    <option value="D"><?php echo $_SESSION["name4"];?></option> </select>

My issue is how I can change this, currently if within the form, any names are left blank then when it comes to the SELECT, there is a blank line for every option blank, is there a way to change this and if a variable is blank then ignore and use the next variable, this would then make my SELECT look tidy

2
  • Just put an if condition. Commented Feb 24, 2014 at 9:42
  • IMO You should use some collection to store the options. Iterate over it to remove not-required and then iterate to display. Or directly put a check before displaying the option while iterating. Commented Feb 24, 2014 at 9:44

3 Answers 3

3

First of all you should consider using an array instead of a series of uniquely named session variable names, e.g.:

$_SESSION['names'] = array('A' => 'First', 'B' => 'Second');

Then you can loop over them with foreach instead. Also the benefit of that would be you can use the array_filter function (documentation) to filter out empty values from your array of names before looping over them:

<select class="select2_category form-control" data-placeholder="Choose a Category" tabindex="1" id="householder" name="householder">
<option value=""></option>
<?php 
$options = array_filter($_SESSION['names']);
foreach ($options as $option_value => $option_name): ?>
  <option value="<?php echo $option_value; ?>"><?php echo $option_name;?></option>
<?php endforeach; ?>
</select>
Sign up to request clarification or add additional context in comments.

Comments

1
<?php if (isset($_SESSION["name1"]) && $_SESSION["name1"]!='') {?><option value="A"><?php echo $_SESSION["name1"];?></option><?php } ?>

this for every line/option of your select

Comments

1

use an if statement to check if your variable exists.

<?php if (isset($_SESSION["name1"])) : ?>
    <option value="C"><?php echo $_SESSION["name1"];?></option>
<?php endif; ?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.