Conditional statement inside string inside php - php

I am trying to evaluate date[3] to determine selected option. All this is inside a php sql query. I am not able to find out an easy way to get a selected for the value returned in date[3] in my $options string variable.
<?php //sql statement
foreach( $db->query($sql) as $data ) {
$options = "<select type='text' name='pagephone' select id='pagephone' >
<option value=''></option>
<option ". if ($data[3] == 'vtext.com' ){ echo 'selected' };. " value='vtext.com'>Verizon Wireless</option>
<option ". if ($data[3] == 'vmobl.com' ){ echo 'selected' };. " value='vmobl.com'>Virgin Mobile</option>
<option ". if ($data[3] == 'sms.alltelwireless.com' ){ echo 'selected' };. " value='sms.alltelwireless.com'>Alltel</option>";
?>

You're trying to concatenate a value with ., so the value you use needs to be an expression that evaluates to a string. An if block is not such an expression, as you can see from the syntax error you get if you use the code from your question. You can use a ternary expression instead, like this.
...<option ". ($data[3] == 'vtext.com') ? 'selected' : '' . " value='vtext.com'>
Verizon Wireless</option>...
Personally, I would prefer to iterate an array of value/text pairs rather than hardcoding all the select options, like this:
$values = [
'vtext.com' => 'Verizon Wireless',
'vmobl.com' => 'Virgin Mobile',
'sms.alltelwireless.com' => 'Alltel'
];
foreach( $db->query($sql) as $data ) {
$options = "<select type='text' name='pagephone' id='pagephone'><option value=''></option>";
foreach ($values as $value => $text) {
$selected = ($data[3] == $value) ? 'selected' : '';
$options .= "<option value='$value' $selected>$text</option>";
}
$options .= '</select>';
}
But that's just my opinion. Don't forget to close your <select>, though.

Related

PHP shows array keys 1 number higher

I want to get all keys of an array showing on my page.
Right now I have this:
$subjectcodes[1] = "Mathematics";
$subjectcodes[2] = "Physics";
$subjectcodes[3] = "Charlie";
$subjectcodes[4] = "Chemistry";
$subjectcodes[5] = "Biology";
$subjectcodes[6] = "English";
$subjectcodes[7] = "Dutch";
$subjectcodes[8] = "German";
$subjectcodes[9] = "Sociology";
$subjectcodes[10] = "Physical Education";
$subjectcodes[11] = "Art";
$subjectcodes[12] = "General Science";
$subjectcodes[13] = "Philosophy";
$subjectcodes[14] = "Management and Organization";
$subjectcodes[15] = "Research and Design";
foreach ($subjectcodes as &$value) {
$key = key($subjectcodes);
echo "<option value=" . $key . ">" . $value . "</option>";
}
When I go to my page with that code I get:
<option value=2>Mathematics</option>
<option value=3>Physics</option>
<option value=4>Charlie</option>
<option value=5>Chemistry</option>
<option value=6>Biology</option>
<option value=7>English</option>
<option value=8>Dutch</option>
<option value=9>German</option>
<option value=10>Sociology</option>
<option value=11>Physical Education</option>
<option value=12>Art</option>
<option value=13>General Science</option>
<option value=14>Philosophy</option>
<option value=15>Management and Organization</option>
<option value=>Research and Design</option></select>
As you can see all keys are 1 higher number then supposed. And the last option doesn't even have a key...
Does anyone why this is, and how I can solve this?
Thanks!
Try:
foreach ($subjectcodes as $key=>$value) {
//$key = key($subjectcodes);
echo "<option value=" . $key . ">" . $value . "</option>";
}
you can use key and value in foreach(), so change:
foreach ($subjectcodes as &$value) {
$key = key($subjectcodes);
echo "<option value=" . $key . ">" . $value . "</option>";
}
to
foreach ($subjectcodes as $key => $value) {
echo "<option value=" . $key . ">" . $value . "</option>";
}
Foreach iterates over the array, this means that when you use the key method the "current" array element is the next on your foreach cycle. Your code is not well constructed for what you are trying to acomplish.
Use this instead:
foreach ($subjectcodes as $key => $value) {
echo "<option value=" . $key . ">" . $value . "</option>";
}
Note: Unless you want to change the value of the array element inside the foreach cycle there is no need to use &$value.
A note to complete the info about using reference as foreach loop variables:
From http://php.net/manual/en/control-structures.foreach.php:
Reference of a $value and the last array element remain even after
the foreach loop. It is recommended to destroy it by unset().
So if you decided to use a reference as a foreach variable, you have unset it after the foreach.
foreach ($subjectcodes as &$value)
{
}
unset($value)

"Array" is displaying in dropdown instead of values fetched from database

code snippet from html_form_class
<?php
$frmStr = $frm->addSelectList(
'city',
$city,
true,
'',
'--- Select City ---',
array(
'class' => 'dropdown-style5',
'id' => 'city'));
echo $frmStr; ?>
code snippet from seachcar.php
$city = $db->select('City','City_Name');
foreach($city as $row)
{
$row;
}
"Array" is displaying in dropdown instead of values fetched from database
Please Advice!
function addSelectList($name, $option_list, $bVal = true, $selected_value = NULL,
$header = NULL, $attr_ar = array() ) {
$str = "<select name=\"$name\"";
if ($attr_ar) {
$str .= $this->addAttributes( $attr_ar );
}
$str .= ">\n";
if ( isset($header) ) {
$str .= " <option value=\"\">$header</option>\n";
}
foreach ( $option_list as $val => $text ) {
$str .= $bVal? " <option value=\"$val\"": " <option";
if ( isset($selected_value) && ( $selected_value === $val || $selected_value === $text) ) {
$str .= $this->xhtml? ' selected="selected"': ' selected';
}
$str .= ">$text</option>\n";
}
$str .= "</select>";
return $str;
}
html output of addSelectList function is
<select name="city" class="dropdown-style5" id="city">
<option value="">--- Select City ---</option>
<option value="0">Array</option>
<option value="1">Array</option>
<option value="2">Array</option>
<option value="3">Array</option>
You need to rebuild the array of cities:
$city = $db->select('City','City_Name');
$city_rebuild = array();
foreach($city as $row) {
$city_rebuild[] = $row['City_Name'];
}
$city = $city_rebuild;
You do echo of array. Something is wrong in your abstraction objects. You must iterate on array to show up its values.
function addSelectList creates a "dropdown" (actually a select element)
You need to remove the html from the function output.
Edit 1
I was confused as to what you were going for. In your foreach($option_list... you need to know what keys are available in the $option_list array and what you want to appear in the select dropdown.

Multiple select by array

I have:
$selectedItem = '100,200,300';
And mysql load:
<select multiple="multiple" name="product_id">
<?php
$query = mysql_query("SELECT * FROM products ORDER BY id");
while($row = mysql_fetch_array($query)){
echo '<option value="$row[id]">$name</option>';
}
?>
</select>
And I need $selectedItem (three values) to be:
<option value="$row[id]" selected>$row[id]</option>
How can I do that? I just can't find the solution when the selectedItem more than 1.
You should make your $selectedItem variable an array (and name it plural since it can have multiple values; just my added preference =P):
$selectedItems = array(100, 200, 300);
Doing this, you'll be able to check if the current row's id is in the array or not (with in_array()) and then "select" that row:
while($row = mysql_fetch_array($query)) {
$selected = in_array($row['id'], $selectedItems) ? ' selected="selected"' : '';
echo '<option value="' . $row[id] . '"' . $selected . '>' . $row['id'] . '</option>';
}
Alternatively, if you can't "define" your list of selected items as an array and you will only have a comma-separated string, you can use explode() to turn it into an array:
$selectedItems = explode(',', $selectedItem);
This will split the $selectedItem variable by commas into an array stored into $selectedItems (usable with the above code).
You can do it like this:
while($row = mysql_fetch_array($query)){
if ( str_pos( $selectedItem.',' , $row[id].',' ) !== false) {
$sel = 'selected';
} else {
$sel = '';
}
echo "<option value='$row[id]' $sel>$row[id]</option>";
}

Why does this PHP function call work only once?

I've wrote a simple array, and I would use it to print an html list option set, with a selected element.
My problem starts if I try to print multiple lists in my page, because only the first list is printed correctly, why?
<?php
$units = array (
'0' => 'Units',
'kJ' => 'Kilojoule: kJ',
'g' => 'Grams: g',
'mg' => 'Milligrams: mg',
'mcg' => 'Micrograms: mcg, µg');
function unit_select_option ($attributes, $code = "") {
global $units;
$html = "<select title=\"Kilojoule: kJ;
Grammi: g;
Milligrammi: mg;
Microgrammi: mcg, µg;\" $attributes>\r";
while (list($key, $name) = each($units)) {
if ($key == "0") {
$html .= " <option title=\"$name\" value='$key'>$name</option>\r";
} else if ($key == $code) {
$html .= " <option title=\"$name\" selected=\"selected\" value='$key'>$key</option>\r";
} else {
$html .= " <option title=\"$name\" value='$key'>$key</option>\r";
}
}
$html.= "</select>\r";
return $html;
}
print unit_select_option ('class="units_select"', "g");
print unit_select_option ('class="units_select"', "mg");
print unit_select_option ('class="units_select"', "mcg");
?>
the code shouldn't be nothing strange but I haven't found the issue because the page doesn't return any error.
html code:
<select title="Kilojoule: kJ;
Grammi: g;
Milligrammi: mg;
Microgrammi: mcg, µg;" class="units_select">
<option title="Unità" value='0'>Unità</option>
<option title="Kilojoule: kJ" value='kJ'>kJ</option>
<option title="Grammi: g" selected="selected" value='g'>g</option>
<option title="Milligrammi: mg" value='mg'>mg</option>
<option title="Microgrammi: mcg, µg" value='mcg'>mcg</option>
</select>
<select title="Kilojoule: kJ;
Grammi: g;
Milligrammi: mg;
Microgrammi: mcg, µg;" class="units_select">
</select>
<select title="Kilojoule: kJ;
Grammi: g;
Milligrammi: mg;
Microgrammi: mcg, µg;" class="units_select">
</select>
each() advances the internal array cursor. Because $units is a global variable, your first call of unit_select_option() advances the cursor to the end of $units, and there it remains for the subsequent calls.
You need to rewind your array using reset($units); at the end of unit_select_option().
PHP Documentation: reset
You should reset the array pointer: use reset()
But why don't you use a foreach loop?
foreach($units as $key => $name){ ... }
And don't use global, it's evil. Declare $units array as static within the function body.
From each():
Return the current key and value pair
from an array and advance the array
cursor.
After each() has executed, the array
cursor will be left on the next
element of the array, or past the last
element if it hits the end of the
array. You have to use reset()
if you want to traverse the array
again using each.
So:
function unit_select_option ($attributes, $code = "") {
global $units;
$html = "<select title=\"Kilojoule: kJ;
Grammi: g;
Milligrammi: mg;
Microgrammi: mcg, µg;\" $attributes>\r";
reset($units);
while (list($key, $name) = each($units)) {
if ($key == "0") {
$html .= " <option title=\"$name\" value='$key'>$name</option>\r";
} else if ($key == $code) {
$html .= " <option title=\"$name\" selected=\"selected\" value='$key'>$key</option>\r";
} else {
$html .= " <option title=\"$name\" value='$key'>$key</option>\r";
}
}
$html.= "</select>\r";
return $html;
}
I tend to avoid each() because its non-reentrant, meaning if inside your loop you call something else that uses it on the same array it'll affect your outer call. Not good. You tend to be better off just using a foreach loop:
function unit_select_option ($attributes, $code = "") {
global $units;
$html = "<select title=\"Kilojoule: kJ;
Grammi: g;
Milligrammi: mg;
Microgrammi: mcg, µg;\" $attributes>\r";
foreach ($units as $key => $name) {
if ($key == "0") {
$html .= " <option title=\"$name\" value='$key'>$name</option>\r";
} else if ($key == $code) {
$html .= " <option title=\"$name\" selected=\"selected\" value='$key'>$key</option>\r";
} else {
$html .= " <option title=\"$name\" value='$key'>$key</option>\r";
}
}
$html.= "</select>\r";
return $html;
}
and you avoid all those issues.
You need to reset your array after or before your while block.
The other answers should have already solved your question.
I want to add that PHP has the foreach construct, so instead of the while loop you can just write
foreach ($unit as $key => $name) {
...
}
You don't need to reset() if you use foreach.
Ok, as others have said the problem was because you weren't resetting the global array.
However, I'd be tempted not to use a global and instead pass it into the unit_select_option every time. (Arrays and objects are passed by reference in recent versions of PHP, so there's no reason not to do this and it's generally accepted as better programming practice.)
Secondly, you're doing some wierd things in the while loop - I'd have thought a foreach iterator would make more sense in this instance as such:
foreach($units as $key => $value)
Just an idea. :-)

Simple way to select chosen option in <select> from the value given by $_POST?

How can i add the selected="selected" bit to the option in an HTML <select> input from the sent $_POST data without an if statement within each option?
<?php
$options = array(1 => 'Banana', 2 => 'Apple');
foreach ($options as $key => $value) {
echo '<option value=""';
if ($key == $_POST['fruit']) echo ' selected="selected"';
echo '>'.$value.'</option>';
}
?>
Programatically, you could do it like this:
$optionNames = array('This', 'Is', 'A', 'Test');
echo '<select id="testselect" name="testselect">';
foreach($optionNames as $currentOption) {
echo '<option value="'.$currentOption.'"';
echo $_POST['testselect'] == $currentOption ? ' selected="selected"' : '';
echo '>'.$currentOption.'</option>';
}
echo '</select>';
Must confess I don't have a dev box up at the moment to test the above code, but it should be OK. (Apologies if not.) :-)
I suppose using an if statement for each option is most efficient.
But you can create an array containing empty strings except for the location of the option you want to select in order to eliminate the if statement.
$options = array(1 => 'Banana', 2 => 'Apple', 3 => 'Orange');
$selected_options = array_fill(1, sizeof($options), "");
if(array_key_exists($_POST['fruit'], $options))
$selected_options[$_POST['fruit']] = " selected=\"selected\"";
echo '<select id="fruit" name="fruit">';
foreach($options as $optionId => $optionText)
echo '<option value="'.$optionId.'"'.$selected_options[$optionId].'>'.$optionText.'</option>';
echo '</select>';

Categories