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... ]
?>
Related
I have problem with my codes and I'm still new to php. Please help me :)
echo "<td><select>
<option value='1'<?php if($row['Staf_Kamp'] == '1') { ?> selected='selected'<?php } ?>>1</option>;
<option value='2'<?php if($row['Staf_Kamp'] == '2') { ?> selected='selected'<?php } ?>>2</option>;
<option value='3'<?php if($row['Staf_Kamp'] == '3') { ?> selected='selected'<?php } ?>>3</option>;
</select></td>";
I am expecting the dropdown list that I have selected before edit will be selected in the edit page. But it is not working.
When echoing, you are already in a php context, so there is no need to use <?php ?> tags again. You can just concatenate the variables in your string.
echo "<td><select>
<option value='1'" . ($row['Staf_Kamp'] == '1' ? ' selected="selected"' : '') . ">1</option>;
<option value='2'" . ($row['Staf_Kamp'] == '2' ? ' selected="selected"' : '') . ">2</option>;
<option value='3'" . ($row['Staf_Kamp'] == '3' ? ' selected="selected"' : '') . ">3</option>;
</select></td>";
Try this:
<td><select>
<option value='1'<?php if($row['Staf_Kamp'] == '1') { echo ' selected'; } ?>>1</option>
<option value='2'<?php if($row['Staf_Kamp'] == '2') { echo ' selected'; } ?>>2</option>
<option value='3'<?php if($row['Staf_Kamp'] == '3') { echo ' selected'; } ?>>3</option>
</select></td>
You only need ; when working inside the <?php ?> tags so strip those out. Also save the opening and closing by just echoing out the selected value. Also the correct syntax is selected and not selected='selected'
you can not echo a string and put php code into the string
correct code:
<td>
<select>
<option value='1'<?php if($row['Staf_Kamp'] == '1') { ?> selected='selected'<?php } ?>>1</option>
<option value='2'<?php if($row['Staf_Kamp'] == '2') { ?> selected='selected'<?php } ?>>2</option>
<option value='3'<?php if($row['Staf_Kamp'] == '3') { ?> selected='selected'<?php } ?>>3</option>
</select>
</td>
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>
}
}
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>');
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>';
I want to presist (=keep values if error on form) my values from a dropdown menu , this is what i started with :
...
$priorities = array('low','normal','high');
...
<select name="priority" id="priority">
<?php
foreach ($priorities as $pro){
echo '<option value="'.$pro.'">'.$pro.'</option>';
}
?>
</select>
It does the job but does not presist.
Now i want to get to something like this :
<select name="priority" id="priority">
<?php
$tel = 0;
foreach ($priorities as $pro){
echo '<option value="'.$tel.'"'.htmlentities('<?php if (isset($_POST[\'priority\']) && (int) $_POST[\'priority\'] === tel) { echo \'selected="selected"\'; } ?>').' >'.$pro.'</option>';
$tel++;
}
?>
</select>
But that of course gives an error.
Anyone has any suggestions thx
Here's how I often implement this:
<select name="priority" id="priority">
<?php
foreach ($priorities as $pro)
{
$selected = (isset($_POST['priorities']) && $pro == $_POST['priority']) ? 'selected' : '';
echo '<option value="' . $pro . '" '.$selected.'>' . $pro . '</option>';
}
?>
</select>
Just thought I'd point out you can actually shorten the ternary here like so
<select name="priority" id="priority">
<?php
foreach ($priorities as $pro)
{
$selected = ($pro == #$_POST['priority']) ? 'selected' : '';
echo '<option value="' . $pro . '" '.$selected.'>' . $pro . '</option>';
}
?>
</select>
Sorry I've got a bit of a thing for creating the shortest code possible :)
Change the second part of the code to:
<select name="priority" id="priority">
<?php
foreach ($priorities as $pro) {
if (isset($_POST['priority']) && $_POST['priority'] == $pro) {
$selected = 'selected="selected"';
}
else {
$selected = null;
}
echo '<option value="'.$pro.'" '.$selected.'>'.$pro.'</option>';
}
?>
</select>
Try this
<select name="priority" id="priority">
<?php
$tel = 0;
foreach ($priorities as $pro){
echo '<option value="'
.$tel
.'"'
.(isset($_POST['priority']) && (int)$_POST['priority'] === $tel)?'selected="selected"':''
.' >'
.$pro
.'</option>';
$tel++;
}
?>
</select>
$priority= array (1=>"low","normal","high");
$select = "<select name=\"priority\"> ;
foreach ($priority as $key => $val) {
$select .= "\t<option val=\"".$key."\"";
if ($val == $yourcheckedvariable) {
$select .= " selected=\"selected\">".$val."</option>\n";
} else {
$select .= ">".$val."</option>\n";
}
}
$select .= "</select>";
echo $select;
use this code