if statement within echo within foreach - php

I am trying to set selected on an <option> based on an array, and I'm close, but not quite getting there...
$departments = array("Finance", "IT", "Retail",);
foreach($departments as $list){
echo '<option';
if($found['dept'] == '$list'){ // if I set this manually it works, but not now
echo ' selected';
}
echo ' >' . $list . ' </option>'; // this works fine to show me the list
}
If I set $found[dept] manually like below, echoing 'selected' works great, but I don't want to write a version of this line for every option.
if($found['dept'] == 'Finance'){ echo 'selected';} > ' .$list . '</option>

Your variable is in single quotes which makes it a string. It's cleaner and easier to see errors like that if you break out your logic from your output.
$departments = array("Finance", "IT", "Retail",);
foreach($departments as $list){
$selected = ($found['dept'] == $list) ? ' selected' : '';
echo "<option$selected>$list</option>";
}

Related

PHP - Syntax error when using ternary operator

Need to add the selected attribute to the matching condition. I'm passing the $fetch_state_db as the function parameter which is getting as expected. Please let me know where is the syntax error.
An uncaught Exception was encountered
Type: ParseError
Message: syntax error, unexpected '' value="'' (T_CONSTANT_ENCAPSED_STRING)
$output = '<option value="">Select State</option>';
foreach($query->result() as $row)
{
$output .= '<option '($row->id==$fetch_state_db)?'selected="selected"':''' value="'.$row->id.'">'.$row->region.'</option>';
}
return $output;
Simpler to read and maintain if you dont try and crush everything into the one line. And also if you use " so the variables will auto expand, and use ' quote to wrap the html element attributes.
$output = '<option value="">Select State</option>';
foreach($query->result() as $row) {
$sel = $row->id==$fetch_state_db ? "selected='selected'" : '';
$output .= "<option $sel value='{$row->id}'>{$row->region}</option>";
}
The code should be:
$output .= '<option '. ($row->id==$fetch_state_db)?'selected="selected"':''. ' value="'.$row->id.'">'.$row->region.'</option>';
Easier to read
$output = '<option value="">Select State</option>';
foreach($query->result() as $row)
{
$selected = $row->id== $fetch_state_db ? 'selected="selected"':"" ;
$output .= '<option '.$selected.' value="'.$row->id.'">'.$row->region.'</option>';
}
return $output;
Well it is issue of concatenation. Use the following
output .= '<option '.($row->id==$fetch_state_db ?'selected="selected"':''' ).' value="'.$row->id.'">'.$row->region.'</option>';
}
Sorry i am using mobile.
You have too many single quotes (') in the second part of you ternary.
Try using double quotes instead of single. In my opinion I think it's a little more readable.
foreach($query->result() as $row)
{
$output .= "<option " . ($row->id == $fetch_state_db ? 'selected="selected"' : "") . " value=\"$row->id\">$row->region</option>";
}
return $output;

Input <select> selected is not working correctly in PHP by comparing 2 arrays

I have
3 <select></select>
with 8 options inside (Array_1 with 8 position). All options value are the same.
What i am trying to do is that I want to make the Value in Array_2 to be the Selected value.
However, looks like my loop is not working correctly.
$array_1[]="value1";
$array_1[]="value2";
$array_1[]="value3";
$array_1[]="value4";
$array_1[]="value5";
$array_1[]="value6";
$array_1[]="value7";
$array_1[]="value8";
$array_2[]="value1";
$array_2[]="value3";
$array_2[]="value4";
for($i=0;$i<count($array_2);$i++){
echo '<select name="product_header_image[]">';
for($b=0;$b<count($array_1);$b++){
if(in_array($array_2[$i],$array_1)){
echo '<option selected VALUE="'.$array_1[$b].'" >'.$array_1[$b].'</option>';
}else{
echo '<option VALUE="'.$array_1[$b].'" >'.$array_1[$b].'</option>';
}
}
echo '</select>';
echo '<br>';
}
Anyone know whats wrong with my coding? what I want to achieve is the right hand side of the screenshot.
You need to replace this check:
if(in_array($array_2[$i], $array_1)) {
...
}
on this:
if($array_2[$i] == $array_1[$b]) {
...
}
Demo here
Not sure I understand your scenario, but this might be what you are looking for. It generates a dropdown with all the elements from both arrays, and highlights the selected ones.
$array_1[]="value1";
$array_1[]="value2";
$array_1[]="value3";
$array_1[]="value4";
$array_1[]="value5";
$array_1[]="value6";
$array_1[]="value7";
$array_1[]="value8";
$array_2[]="value1";
$array_2[]="value3";
$array_2[]="value4";
echo '<select name="product_header_image[]" multiple>';
foreach ($array_1 as $elem1) {
echo '<option VALUE="'. $elem1 .'" >' . $elem1 .'</option>';
}
foreach ($array_2 as $elem2) {
$selected = '';
if( in_array($elem2, $array_1) ) $selected = 'selected ';
echo '<option '. $selected . 'VALUE="' . $elem2 . '" >'.$elem2.'</option>';
}
echo '</select>';
echo '<br>';

Keep option selected

I have a selectbox with some values, i inserted those values inside an array.
Now i want to select some specific option, and keep the option selected even when the page reloads.
$logos =array('logo1', 'logo2', 'logo3');
echo '
<td class="jofftd">
<label>Platform</label>
<select name="searchpt">
<option value="0">All</option>
';
foreach ($logos as $value)
{
echo '
<option value="'.$value.'">' .$value . '</option>
';
}
echo '
</select>
</td>';
I would need to do something like this:
foreach ($logos as $value)
{
echo '
<option';
if ($value == $value) echo 'selected="selected"';
echo 'value="'.$value.'">' .$value . '</option>
';
}
But it doesn't work.
Thanks.
Assuming you are using a POST method form, the code would look something like this (note: not tested)
foreach ($logos as $value)
{
$selected = ($value == $_POST['searchpt']) ? ' selected' : '';
echo '<option'. $selected . ' value="'.$value.'">' .$value . '</option>';
}
If nothing else, you're missing at least one space character:
<option';
if ($value == $value) echo 'selected="selected"';
This will produce
<optionselected="selected"
which is not exactly valid HTML.
Plus, $value==$value will always be true, so even if you had proper spacing in the tags, you'd be marking ALL of the options as selected. You need to compare the $value from the loop against the value from the original form, e.g.
if ($value == $_POST['field_from_previous_form'}) { ... }
$value == $value will be always true and it will always add selected = "selected"
use string concatenation to form select form field.
<?php
$logos =array('logo1', 'logo2', 'logo3');
$value = 'logo1';
$str = '<select name="searchpt"><option value="0">All</option>';
foreach ($logos as $value)
{
$str.='<option ';
if ($value == 'logo1')
$str.=' selected="selected "';
$str.=' value="'.$value.' ">' .$value . ' </option> ';
}
$str.='</select>';
echo $str;
?>
Hope this code snippet will solve your problem

Get selected dropdown option from database using PHP

I have a dropdown section menu that I need to set the selected value based on the database values.
I have a table with the following structure: id, pid, disporder, title, url
I am then using this code for the dropdown:
echo "<select name=\"parent\" id=\"parent\">\n";
echo "<option value=\"0\">No Parent</option>";
$query = $db->simple_select("navbar", "*", "pid='0'");
while($parent = $db->fetch_array($query))
{
echo "<option value=\"".$parent['id']."\">".$parent['title']."</option>";
}
echo "</select>";
How would I go by getting the selected value based on what's in the database?
I have multiple entries in the table, so using an array with values (similar to this), isn't what I want to use:
$options = array('1', '2', '3');
foreach($options as $option)
{
if($option = $parent['id'])
{
echo "selected";
}
else
{
echo "";
}
Thanks.
You haven't really given enough info to really say what the exact solution would be. If you're creating a select tag in PHP though, the typical pattern for building the markup is:
<?php
$options = get_me_some_options();
$select_markup = '<select name="my-select" id="my-select>';
foreach ($options as $key => $val) {
$selected = '';
if (is_this_selected($val)) {
$selected = 'selected';
}
$select_markup .= "<option $selected val=\""
. $val['id'] . "\">" . $val['name'] . '</option>';
}
echo $select_markup . "</select>";
It looks like your use case is similar, but slightly more complex. Ultimately though what matters is that, inside the loop, you have some way to determine whether a given row should be 'selected' or not.
If I understand correctly, you want to compare each $parent['id'] with the values of an array called $options. Try this:
$options = array('1', '2', '3');
echo "<select name=\"parent\" id=\"parent\">\n";
echo "<option value=\"0\">No Parent</option>";
$query = $db->simple_select("navbar", "*", "pid='0'");
while($parent = $db->fetch_array($query))
{
$selected = ( in_array($parent['id'], $options) ? ' selected' : '';
echo "<option value=\"".$parent['id']."\"$selected>".$parent['title']."</option>";
}
echo "</select>";
If you're trying to use this in multiselects then this might help
<?php
$optionsToSelect=array(1,2,3);
?>
<select name="parent" id="parent">
<?php
foreach($allOptions as $opt){
?>
<option value="<?php echo $opt['value'];?>" <? echo $opt['selected']==1?'selected="selected"':'';?>><?php echo $opt['optTitle'];?><option>
<?php
}
?>
</select>

Populate drop down list from database

I`m using this code to repopulate drop down list from the database :
$city_id = 15;
while($row = mysql_fetch_assoc($result)) {
$selected = ($row['city_id'] == $city_id) ? 'selected="selected" ' : NULL;
echo '<option value="'.$city_id .$selected . '">"'.$row['city_name'].'"</option>\n';
}
It`s work like a charm but my question is are they more elegance solutions ?
Other than improving the indentation of the code, this is fine.
$city_id = 15;
while($row = mysql_fetch_assoc($result))
{
$selected = ($row['city_id'] == $city_id) ? ' selected="selected"' : NULL;
echo '<option value="' . $row['city_id']. '"' . $selected . '>'.$row['city_name'].'</option>\n';
}
Well, a more elegant solution would be to have a "controller" file that fetches all the cities an puts them into an array/object list/whatever. Then, in a "view" file, you iterate over that variable. That way, you separate a bit more the presentation from the logic.
In view:
<select name=student value=''>Student Name</option>
<?php foreach($cities as $city): ?>
<option value="<?php echo $city->id ?>" ><?php echo $city->name ?></option>
<?php endforeach; ?>
</select>
Also, I'd highly recommend using PDO for DB access.
I always use a function, since select boxes are something I end up creating a lot...
function select($name, $default, $values, $style='', $param='') {
$html = '<select name="'.$name.'" style="'.$style.'" '.$param.' >';
foreach($values as $i => $data) {
if (isset($data['noFormat'])) {
$html .= '<option value="'.$data['value'].'" '.(($data['value']==$default)?'SELECTED="SELECTED"':'').' '.
(isset($data['style']) ? ' style="'.$data['style'].'" ' : '').'>'.$data['text'].'</option>';
} else {
$html .= '<option value="'.htmlentities($data['value']).'" '.(($data['value']==$default)?'SELECTED="SELECTED"':'').' '.
(isset($data['style']) ? ' style="'.$data['style'].'" ' : '').'>'.htmlentities($data['text']).'</option>';
}
}
$html .= '</select>';
return $html;
}
Then loop through your query to build the array like this:
$default[] = array('value' => '0', 'text' => 'Select a City...');
while($row = mysql_fetch_assoc($result)) {
$list[] = array('value' => $row['city_id'], 'text' => $row['city_name']);
}
$list = array_merge($default,$list);
And finally an example to create the HTML:
select('select','form_el_name',$list['0'],$list,'font-size:12px;','onChange="document.forms[0].submit();"');
Hope it helps!
mysql_fetch_assoc to mysql_fetch_array
add proper comments
use standard php class ezsql or simple class tuts
$query="SELECT name,id FROM student";
/* You can add order by clause to the sql statement if the names are to be displayed in alphabetical order */
$result = mysql_query ($query);
echo "<select name=student value=''>Student Name</option>";
// printing the list box select command
while($nt=mysql_fetch_array($result)){//Array or records stored in $nt
echo "<option value=$nt[id]>$nt[name]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";//Closing of list box

Categories