abby abby - 25 days ago 10
PHP Question

shorten the code using for each loop

<?php
if (isset($_SESSION["employee_type"])) { // For Updating the Employee Data
if ($_SESSION['employee_type'] == "Manager") {
echo "<option value='Manager'>Manager</option>";
echo "<option value='Programmer'>Programmer</option>";
echo "<option value='Full Stack Developer'>Full Stack Developer</option>";
echo "<option value='Clerk'>Clerk</option>";
echo "<option value='Peon'>Peon</option>";
} else if ($_SESSION['employee_type'] == "Programmer") {
echo "<option value='Programmer'>Programmer</option>";
echo "<option value='Manager'>Manager</option>";
echo "<option value='Full Stack Developer'>Full Stack Developer</option>";
echo "<option value='Clerk'>Clerk</option>";
echo "<option value='Peon'>Peon</option>";
} else if ($_SESSION['employee_type'] == "Full Stack Developer") {
echo "<option value='Full Stack Developer'>Full Stack Developer</option>";
echo "<option value='Manager'>Manager</option>";
echo "<option value='Programmer'>Programmer</option>";
echo "<option value='Clerk'>Clerk</option>";
echo "<option value='Peon'>Peon</option>";
} else if ($_SESSION['employee_type'] == "Clerk") {
echo "<option value='Clerk'>Clerk</option>";
echo "<option value='Manager'>Manager</option>";
echo "<option value='Programmer'>Programmer</option>";
echo "<option value='Full Stack Developer'>Full Stack Developer</option>";
echo "<option value='Peon'>Peon</option>";
} else {
echo "<option value='Peon'>Peon</option>";
echo "<option value='Clerk'>Clerk</option>";
echo "<option value='Manager'>Manager</option>";
echo "<option value='Programmer'>Programmer</option>";
echo "<option value='Full Stack Developer'>Full Stack Developer</option>";
}
?>
<?php } ?>


This code automatically fills the Employee Type dropdown when we want to update the data.

Problem is given below :

I want to shorten this code , but i don't know how , Please help

Answer Source

please try this you want to default selected the employee type of session value from $_SESSION['employee_type']

<?php
if (isset($_SESSION["employee_type"])) {// For Updating the Employee Data
    $employee_type = $_SESSION['employee_type'];

  ?>
    <option value='Manager' <?php if($employee_type == 'Manager'){ echo "selected";} ?>>Manager</option>
    <option value='Programmer' <?php if($employee_type == 'Programmer'){ echo "selected";} ?>>Programmer</option>
    <option value='Full Stack Developer' <?php if($employee_type == 'Full Stack Developer'){ echo "selected";} ?>>Full Stack Developer</option>";
    <option value='Clerk' <?php if($employee_type == 'Clerk'){ echo "selected";} ?>>Clerk</option>
    <option value='Peon' <?php if($employee_type == 'Peon'){ echo "selected";} ?>>Peon</option>
<?php 

 } ?>