need advise on if-else statement using php - php

I'm trying to add selected in option when condition true. Its working fine, but its giving two times selected.
foreach ($sorts as $sorts) {
if ($cat_id == 59 && $sorts['value'] == 'p.price-ASC') { // True if category id equal to 59
<option value="<?php echo $sorts['href']; ?>" selected="selected"><?php echo $sorts['text']; ?></option>
}else{
if ($sorts['value'] == $sort . '-' . $order) { // True if values are equal
<option value="<?php echo $sorts['href']; ?>" selected="selected"><?php echo $sorts['text']; ?></option>
}else {
<option value="<?php echo $sorts['href']; ?>"><?php echo $sorts['text']; ?></option>
}
}
}
In above you can see there are two conditions for selected.
True if category id equal to 59 if ($cat_id == 59 &&
$sorts['value'] == 'p.price-ASC')
True if values are equal if ($sorts['value'] == $sort . '-' .
$order)
On other category pages it totally working fine, but on category 59 two if statements are giving true. That's why on this page two selected are adding on two option.
<option value="name-az" >Name (A - Z)</option>
<option value="name-az" selected="selected">Name (Z - A)</option>
<option value="p.price-ASC" selected="selected">Price (Low > High)</option>
So can any one guide me how to fix or modify the condition that i can get only one true condition in one time. Thanks

You could solve it by using a new variable $done indicating that the selected value was added already:
$done = false;
foreach ($sorts as $sorts) {
if (!$done && $cat_id == 59 && $sorts['value'] == 'p.price-ASC') { // True if category id equal to 59
<option value="<?php echo $sorts['href']; ?>" selected="selected"><?php echo $sorts['text']; ?></option>
$done = true;
}else{
if (!$done && $sorts['value'] == $sort . '-' . $order) { // True if values are equal
<option value="<?php echo $sorts['href']; ?>" selected="selected"><?php echo $sorts['text']; ?></option>
$done = true;
}else {
<option value="<?php echo $sorts['href']; ?>"><?php echo $sorts['text']; ?></option>
}
}
}
Problem with the above and your code is that the foreach is incorrect. $sorts as $sorts is not possible for the foreach. I've refactored your code to more safe and better usable code. This code is also tested and works as expected:
//INPUT:
$sort = 'name';
$order = 'za';
$cat_id = 59;
$sorts = array(
'name-az' => 'Name (A - Z)',
'name-za' => 'Name (Z - A)',
'p.price-ASC' => 'Price (Low > High)',
'p.price-DESC' => 'Price (High > Low)'
);
//CODE:
if(!array_key_exists($sort . '-' . $order, $sorts)) //check your input!
throw new Exception('Invalid sort order.');
$selected = $cat_id == 59 ? 'p.price-ASC' : $sort . '-' . $order;
$done = false;
echo '<select>';
foreach ($sorts as $key => $value) {
echo '<option value="'.htmlentities($key, ENT_QUOTES, 'UTF-8').'"'.($selected==$key?' selected="selected"':'').'>'.htmlentities($value, ENT_QUOTES, 'UTF-8').'</option>';
}
echo '</select>';

Why use 2 if statements? That's what elseif is for. Does this code work for you?
foreach($sorts as $sorts)
{
if($cat_id == 59 && $sorts['value'] == 'p.price-ASC')
{
<option value="<?php echo $sorts['href']; ?>" selected="selected"><?php echo $sorts['text']; ?></option>
continue;
}
elseif($sorts['value'] == $sort . '-' . $order)
{
<option value="<?php echo $sorts['href']; ?>" selected="selected"><?php echo $sorts['text']; ?></option>
continue;
}
else
{
<option value="<?php echo $sorts['href']; ?>"><?php echo $sorts['text']; ?></option>
}
}

Related

PHP - Edit page , How to set default dropdownlist that have option from MySQL?

I know only this method. this method is assume that you know the values in all <option>
<select name="agama" id="agama">
<option value="Islam"<?php if ($rows['agama'] === 'Islam') echo ' selected="selected"'>Islam</option>
<option value="Khatolik"<?php if ($rows['agama'] === 'Khatolik') echo ' selected="selected"'>Khatolik</option>
<option value="Protestan"<?php if ($rows['agama'] === 'Protestan') echo ' selected="selected"'>Protestan</option>
<option value="Hindu"<?php if ($rows['agama'] === 'Hindu') echo ' selected="selected"'>Hindu</option>
<option value="Buddha"<?php if ($rows['agama'] === 'Buddha') echo ' selected="selected"'>Buddha</option>
<option value="Lain-Lain"<?php if ($rows['agama'] === 'Lain-Lain') echo ' selected="selected"'>Lain-Lain</option>
</select>
.... the above code is example from other people not mine.
but My case is the <option> is select from database too.
I have 2 table, oav_event and oav_album
the oav_album has foreign key (event_id) from oav_event table
I want to check if row['event_id'] from oav_album table is equal to option value (from oav_event table) if true, then set selected="selected"
while($row = mysqli_fetch_assoc($result)) { ?>
<option value="<?php echo $row['event_id']; ?>" >Event: <?php echo $row['event_date']; ?> </option>
<?php } ?>
the option will change depend on change in database table, so I don't know the value in option. How should I do?
<select name="event_id">
<?php
$sql = "SELECT * FROM oav_event";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
$selected = "";
if($row['event_id'] == $Yourmatchvalue)
{
$selected = "selected";
}
?>
<option value="<?php echo $row['event_id']; ?>" selected="<?php echo $selected; ?>" >Event: <?php echo $row['event_date']; ?> </option>
<?php } ?>
</select>
may this helps your. you need to replace $Yourmatchvalue variable with your variable.
You can use $_GET as the method on your form and pass the id of the record using it:
while($row = mysqli_fetch_assoc($result)) {
if (!empty($_GET['event_id']) && $row['event_id'] == $_GET['event_id']) {
$selected = 'selected = "selected"';
} else {
$selected = '';
}
echo '<option '.$selected.' value="'.$row["event_id"].'">'.$row["event_date"].'</option>';
}
Here is a solution,
$selected_value = 'Hindu'; // This will come from database
Change option tag with this
<option value="<?php echo $row['event_id']; ?>" <?php echo ($row['event_id'] == $selected_value) ? 'selected="selected"' : ''; ?> >Event: <?php echo $row['event_date']; ?> </option>
Create one function which will create options list like this:
function setDropdownValue($selectQueue_list,$selectedVal)
{
$queueVal = '';
$selectQueue_list_res=$db->query($selectQueue_list);
while($selectQueue_list_res_row=$db->fetchByAssoc($selectQueue_list_res))
{
$val = $selectQueue_list_res_row['id'];
$name = $selectQueue_list_res_row['name'];
if($val == $selectedVal)
{
$queueVal .= "<option value='$val' selected='selected' label='$name'>$name</option>";
}
else
{
$queueVal .= "<option value='$val' label='$name'>$name</option>";
}
}
return $queueVal;
}
Then create a query:
$get_value_query="SELECT id, name FROM table";
$dropdown_selected_value = !empty($dropdown_value) ? $dropdown_value: ''; // Pass value which you want to be selected in dropdown
Then call this function:
$dropdown_options = setDropdownValue($get_value_query, $dropdown_selected_value);
Later when you get dropdown options in $dropdown_options, use jquery to populate the dropdown, like this:
$('#dropdown_select_id').html("$dropdown_options");
Give it a try, and let me know.

PHP Select Option from Array list

im new to PHP and im trying this stuff for hours, I wanted to show the Array items to the Select Option. Here's the code:
<select name="state">
<?php
$arrstate=array
(
array("AK","Alaska"),
array("AL","Alabama"),
array("AR","Arkansas"),
array("AZ","Arizona"),
array("CA","California"),
array("CO","Colorado"),
array("CT","Connecticut"),
array("DC","District of Columbia"),
array("DE","Delaware"),
array("FL","Florida"),
array("GA","Georgia"),
array("HI","Hawaii"),
array("IA","Iowa"),
array("ID","Idaho"),
array("IL","Illinois"),
array("IN","Indiana"),
array("KS","Kansas"),
array("KY","Kentucky"),
);
for($lop=0;$lop<=49;$lop++)
{
if (strtoupper($lead_info['state'])==$arrstate[$lop][0])
{
echo "<option selected=\"selected\" value=\"".$arrstate[$lop][0]."\">".$arrstate[$lop][1]."</option>\n";
}else{
echo "<option value=\"".$arrstate[$lop][0]."\">".$arrstate[$lop][1]."</option>\n";
}
}
?>
</select>
But it seems it only shows ".$arrstate[$lop][1]."
What seems to be the problem?
try it
<?php
$arrstate = array
(
'AK' => 'Alaska',
'AL' => 'Alabama',
'AR' => 'Arkansas',
'AZ' => 'Arizona'
); ?>
<select>
<?php foreach($arrstate as $key => $value) { ?>
<option value="<?php echo $key; ?>" <?=($value == $current_zip_entered ? "selected" : "" )?>><?php echo $value; ?></option>
<?php } ?></select>
<?php
$arrstate=array
(
"AK","Alaska",
"AL","Alabama",
"AR","Arkansas",
"AZ","Arizona"
);
?>
this is the easiest way...
<select>
<?php
foreach($arrstate as $key => $value) {
?>
<option value="<?php echo $key; ?>" <?=($value == $current_zip_entered ? "selected" : "" )?>><?php echo $value; ?></option>
<?php
}
?>
</select>
You can retrieve from database like this example:
<select>
<?php $result = mysqli_query($conn, "SELECT * FROM categories");
while ($row = mysqli_fetch_array($result)) {
$categories = array($row["category"]);
$arrlength = count($categories);
for($x = 0; $x < $arrlength; $x++) {
echo "<option>";
echo $categories[$x];
echo "</option>";
}}?>
</select>

Using a PHP variable to determine a HTML select box choice

I have a select box that when the page loads it sets a value selected based upon a variable. I also have 2 IF statements that checks the variable and returns the results. Here is my code I am trying to do:
<select id="satbreak1" name="satbreak1">
<?php if ($trimmed_title[0] == "Guest")
{
echo ('<option selected value="#">Select One</option>');
echo ('<option value="y">Yes</option>');
echo ('<option value="n">No</option>');
}
if ($trimmed_title[0] != "Guest")
{
echo ('<option <?php if($trimmed_satBreakfast[0] == "") echo ("selected ") ; ?> value="#">Select One</option>');
echo ('<option <?php if($trimmed_satBreakfast[0] == "y") echo ("selected ") ; ?> value="y">Yes</option>');
echo ('<option <?php if($trimmed_satBreakfast[0] == "n") echo ("selected ") ; ?> value="n">No</option>');
}
?>
</select>
What I need to do is if $trimmed_title[0] == "Guest" then echo out the first part, but if $trimmed_title[0] != "Guest") then echo out the second part and also check what the status of $trimmed_satBreakfast[0] is and set the selected value.
What is the best / correct way to handle this?
The first part works fine but having an php script in a echo seems to fail.
I think this might do the trick - not tested but theoretically looks ok
<select id="satbreak1" name="satbreak1">
<?php
if ( $trimmed_title[0] == "Guest" ) {
echo '
<option selected value="#">Select One</option>
<option value="y">Yes</option>
<option value="n">No</option>';
} else {
$tsb=$trimmed_satBreakfast[0];
echo '
<option selected value="#" '.( $tsb=='' ? 'selected' : '' ).'>Select One</option>
<option value="y" '.( $tsb=='y' ? 'selected' : '' ) .'>Yes</option>
<option value="n"'.( $tsb=='n' ? 'selected' : '' ).'>No</option>';
}
?>
</select>
Something like this:
<?php
$options = array(
'values' => array('', 'y', 'n'),
'titles' => array('Select One', 'Yes', 'No')
)
$index = $trimmed_title[0] == 'Guest' ? 0 : array_search($trimmed_satBreakfast[0], $options['values']);
//if ($index === false) $index = 0;
$optHtml = array();
foreach($options['values'] as $i => $val) {
$selected = $index == $i ? 'selected' : '';
$optHtml[] = "<option $selected value=\"$val\">{$options['titles'][$i]}</option>";
}
$optHtml = implode("\n", $optHtml);
?>
<select id="id" name="name">
<?php echo $optHtml?>
</select>
or any other style to split html from php:
//if ($index === false) $index = 0;
...
?>
<select id="id" name="name">
<?php foreach($options['values'] as $i => $val) {?>
<option <?=$index==$i?'selected':''?> value="<?=$val?>">
<?=$options['titles'][$i]?>
</option>
<?php } ?>
</select>
In this case HTML not used in the common php code, but php used in HTML (only general template features: loop through data and echo it).
Common purpose of this is possibility to extract template part to separate file.
It is already PHP so you have to remove the php tags
echo ('<option '.($trimmed_satBreakfast[0] == "") ? : '"selected"' : ''.' value="#">Select One</option>');
echo ('<option '.($trimmed_satBreakfast[0] == "y") ? : '"selected"' : ''.' value="y">Yes</option>');
echo ('<option '.($trimmed_satBreakfast[0] == "n") ? : '"selected"' : ''.' value="n">No</option>');

Echo selected value first

I need to echo the selected value first in a form when user wants to make an update. I tried several variants:
1)
<?php
$opt= array('1' => 'opt1', '2' => 'opt2', '3' => 'opt3') ;
echo '<select name="up_opt" >' ;
foreach ($opt as $i => $value) {
echo "<option value=\"$i\"";
if ($_REQUEST['up_opt'] == $i)
{
echo "selected" ;
}
echo ">$opt[$i]</option>" ;
}
echo '</select>' ;
?>
2)
<?php $opt= array('1' => 'opt1', '2' => 'opt2', '3' => 'opt3') ;
$edu = $_REQUEST['edu'];
<select name="up_opt">
<?php foreach ( $opt as $i=>$opt ) : ?>
<option value="<?php echo $i?>" <?php echo $i == $edu ? 'selected' : ''?>><?php echo $opt ?></option>
<?php endforeach; ?>
</select>
3)
<select name="up_opt">
<option value="1" <?php if ($_GET['1'] == 'option1') { echo 'selected'; } ?>>Opt1</option>
<option value="2" <?php if ($_GET['2'] == 'option2') { echo 'selected'; } ?>>Opt2</option>
<option value="3" <?php if ($_GET['3'] == 'option3') { echo 'selected'; } ?>>Opt3</option>
</select>
None of these variants echoes the checked value first. Can someone help me, tell me what is wrong or give me another variant?
Variant 3 is ok (but I'd rather use a loop instead of hard-coded options). Your mistake is that you compare 'option1', 'option2' and so one when your real values are '1', '2', '3'. Also as #ElefantPhace said, don't forget about spaces before selected, or you'll get invalid html instead. So it would be this:
<select name="up_opt">
<option value="1" <?php if ($_GET['up_opt'] == 1) { echo ' selected="selected"'; } ?>>Opt1</option>
<option value="2" <?php if ($_GET['up_opt'] == 2) { echo ' selected="selected"'; } ?>>Opt2</option>
<option value="3" <?php if ($_GET['up_opt'] == 3) { echo ' selected="selected"'; } ?>>Opt3</option>
</select>
With loop:
<?php
$options = array(
1 => 'Opt1',
2 => 'Opt2',
3 => 'Opt3',
);
?>
<select name="up_opt">
<?php foreach ($options as $value => $label): ?>
<option value="<?php echo $value; ?>" <?php if ($_GET['up_opt'] == 1) { echo ' selected="selected"'; } ?>><?php echo $label; ?></option>
<?php endforeach ?>
</select>
Here is all three of your variants, tested and working as expected. They are all basically the same, you were just using the wrong variable names, and different ones from example to example
1)
<?php
$opt= array('1' => 'opt1', '2' => 'opt2', '3' => 'opt3') ;
echo '<select name="up_opt">';
foreach ($opt as $i => $value) {
echo "<option value=\"$i\"";
if ($_POST['up_opt'] == $i){
echo " selected";
}
echo ">$value</option>";
}
echo '</select>';
?>
2) uses same array as above
$edu = $_POST['up_opt'];
echo '<select name="up_opt">';
foreach ( $opt as $i => $value ){
echo "<option value=\"$i\"", ($i == $edu) ? ' selected' : '';
echo ">$value</option>";
}
echo "</select>";
3)
echo '<select name="up_opt">';
echo '<option value="1"', ($_POST['up_opt'] == '1') ? 'selected':'' ,'>Opt1</option>';
echo '<option value="2"', ($_POST['up_opt'] == '2') ? 'selected':'' ,'>Opt2</option>';
echo '<option value="3"', ($_POST['up_opt'] == '3') ? 'selected':'' ,'>Opt3</option>';
echo '</select>';

How to embed if statement inside echo [duplicate]

This question already has answers here:
if block inside echo statement?
(4 answers)
Closed 11 months ago.
I'm gettin' a headache on that. I need to put if statement inside an echo (this echo is in a function, it's for a form submit actually)
Here is an example on a partial of my code. In this situation, how can I put theses if statement inside my echo??
<?php echo '<td><select id="depuis" name="depuis">
<option value=\'4\' <?php if(isset($_POST[\'depuis\']) && $_POST[\'depuis\'] == \'4\'){ echo \'selected\'; } else { echo ''; } ?> ></option>
<option value=\'1\' <?php if(isset($_POST[\'depuis\']) && $_POST[\'depuis\'] == \'1\'){ echo \'selected\'; } else { echo ''; } ?> >2 ans et moins</option>
<option value=\'2\' <?php if(isset($_POST[\'depuis\']) && $_POST[\'depuis\'] == \'2\'){ echo \'selected\'; } else { echo ''; } ?> >2 à 5 ans</option>
<option value=\'3\' <?php if(isset($_POST[\'depuis\']) && $_POST[\'depuis\'] == \'3\'){ echo \'selected\'; } else { echo ''; } ?> >5 ans et plus</option>
</select>
</td>'
; ?>
Everything is php so need to use more than the first <?php Finish each echo before checking with if. Like this:
<?php
echo '<td><select id="depuis" name="depuis">
<option value="4"';
if(isset($_POST['depuis']) && $_POST['depuis'] == '4') {
echo ' selected';
}
echo ' >Something here maybe?</option>...etc
Use an inline if statement:
echo 'Based on your score, you are a ',($score > 10 ? 'genius' : 'nobody');
This would work - although I'm sure it could be streamlined:
<?php
$out = '
<td>
<select id="depuis" name="depuis">
<option value="4"
';
if(isset($_POST['depuis']) && $_POST['depuis'] == '4'){
$out .= 'selected';
}
$out .= '
></option>
<option value='1'
';
if(isset($_POST['depuis']) && $_POST['depuis'] == '1'){
$out .= 'selected';
}
$out .= '
>2 ans et moins</option>
<option value=\'2\'
';
if(isset($_POST['depuis']) && $_POST['depuis'] == '2'){
$out .= 'selected';
}
$out .= '
>2 à 5 ans</option>
<option value='3'
';
if(isset($_POST['depuis']) && $_POST['depuis'] == '3'){
$out .= 'selected';
}
$out .= '
>5 ans et plus</option>
</select>
</td>
';
echo $out;
?>
Meilleurs voeux...
You will want to use the a ternary operator which acts as a shortened IF/Else statement:
echo '<option value="'.$value.'" '.(($value=='United States')?'selected="selected"':"").'>'.$value.'</option>';
You shouldn't escape the array keys in the string
if(isset($_POST[\'depuis\']) ...
Should be
if(isset($_POST['depuis']) && ...
Also you could clean up the the generation of the options with a array and a loop
$options = array(
'label1' => 1,
'label2' => 2,
'label3' => 3,
'label4' => 4
);
$value = (isset($_POST['depuis'])) ? $_POST['depuis'] : 0;
foreach ($options as $label => $optionValue) {
$selected = ($optionValue == $value) ? ' selected' : '';
printf('<option value="%s"%s>%s</option>', $optionValue, $selected, $label);
}
Not sure you can do that like you're asking. You'd just need to use regular if/else if block and output the outcome separately.
<?php
echo("<td><select id=\"depuis\" name=\"depuis\">");
echo("<option value='4'");
if(isset($_POST['depuis']) && $_POST['depuis'] == '4'){ echo("selected"); }
echo("></option>");
[ ...etc... ]
?>

Categories