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)
Related
I have the following array:
$selects = array(
'Select1' => array('select1_name' => array('select1_value1','select1_value1')),
'Select2' => array('select2_name' => array('select2_value1','select2_value2'))
);
I wonder how I can generate these "selects inputs" with their options through a loop?
You need one cycle, which will loop through selects array and inside this cycle, you need another one, which will loop through selects. And inside this one, you need one more, which will loop through the option values:
$selects = array(
'Select1' => array('select1_name' => array('select1_value1','select1_value1')),
'Select2' => array('select2_name' => array('select2_value1','select2_value2'))
);
foreach($selects as $select) {
foreach($select as $item) {
echo "<select>";
foreach($item as $value) {
echo "<option value=".$value.">".$value."</option>";
}
echo "</select>";
}
}
This will produce:
<select>
<option value=select1_value1>select1_value1</option>
<option value=select1_value1>select1_value1</option>
</select>
<select>
<option value=select2_value1>select2_value1</option>
<option value=select2_value2>select2_value2</option>
</select>
foreach($selects as $select) {
foreach($select as $selectName => $value) {
echo '<select> ';
echo '<option>'.$selectName.'</option>';
foreach($value as $v) {
echo '<option>'.$v.'</option>';
}
echo '</select>';
}
}
echo '<select> ';
foreach($selects as $array) {
foreach($array as $value) {
foreach($value as $v) {
echo '<option value="'.$v.'">'.$v.'</option>';
}}}
echo '</select>';
if(isset($_POST["marketing"])){
foreach($_POST as $key => $value){
if(strlen($value)<1)
continue;
echo "<option value='".$value."' selected >".$value."</option>";
}
I have create dynamic options in php. All option are selected by default . I want to add all selected option into database.
How can i check options is selected or not?
Try this, we do not know what else is being posted through your form though..
if (isset($_POST["marketing"])){
foreach($_POST as $key => $value)
{
$iselected = ($value == $_POST['marketing']) ? 'selected' : '';
echo "<option value='" . $value . "' $iselected>" . $value . "</option>";
}
}
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>";
}
I've tried converting this ASP code to PHP, and would like to know if it is correct:
ASP:
Set emp = Server.CreateObject("Scripting.Dictionary")
EM_GENERAL=0
EM_AUDIO=1
EM_VIDEO=2
emp.Add EM_GENERAL, "General"
emp.Add EM_AUDIO, "Audio"
emp.Add EM_VIDEO, "Video"
For each em in Emp
Response.Write "<option value=" + CStr(em)
If em = CInt(IT_FIELD) Then
Response.Write " selected"
End If
Response.Write ">"
Response.Write Emp.Item(em)
Next
PHP:
$EM_GENERAL=0;
$EM_AUDIO=1;
$EM_VIDEO=2;
$emp = array();
$emp[$EM_GENERAL] = "General";
$emp[$EM_AUDIO] = "Audio";
$emp[$EM_VIDEO] = "Video";
foreach ($emp as $em) {
echo "<option value=" + ($em);
if ($em == intval($IT_FIELD)) {
echo " selected";
}
echo ">";
echo $em;
}
In VB, the For Each loop iterates over the Dictionary keys, not the values, so in your ASP code, em is the numeric key of your emp entries. In PHP, foreach iterates over the values, so $em is the value, not the key. Your if ($em == intval($IT_FIELD)) check will not work as expected. Fortunately the php foreach loop also supports the syntax foreach ($array as $key => $value), where $value would be equivalent to Dictionary.Item(key).
Try this instead:
foreach ($emp as $em => $value) {
echo "<option value=" + ($em);
if ($em == intval($IT_FIELD)) {
echo " selected";
}
echo ">";
echo $value;
}
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. :-)