Help with PHP and associative arrays - php

I have to do a simple calculator in php based on user's input and choice from select field, something like this:
<?php
$a = $_GET['a'];
$b = $_GET['b'];
$array = array( "option1" => 0.1,
"option2" => 0.15,
"option3" => 0.3,
"option4" => 3,
"option5" => 3,
"option6" => 16,
"option7" => 16,
"option8" => 16
);
echo "<form action='calc.php' method='get'>";
echo "<input type='text' name='a' value='".$a."'> of ";
echo "<select name='b'>";
foreach ($array as $k => $v) {
echo "<option value='".$v."'>".$k."</option>";
}
echo "</select> ";
echo "<input type='submit' value='='> ";
$total_volume = $a * $b;
echo $total_volume;
echo "</form>";
?>
Well, for now everything works fine, but the idea is that after user submits form, the page reloads with sent amount in input field and selected option which user actually selected...
First thing is easy: I just put value="a" in my input field, but I'm not sure how to make a selected option in <select> field???
I started with this:
foreach ($array as $k => $v) {
echo "<option value='".$v."'";
if ($b == $v) {
echo " selected ";
}
echo ">".$k."</option>";
}
...but this is obviously not working as expected... Please help me with this easy one :)
Thanks!

You need to echo something like 'selected="selected"'. The rest of the code seems fine to me.
On second thought there is something structurally wrong as multiple options return the same value, making it impossible to select the right one after submitting the form.
You will need to send $k as the value in the select in your loop and for your calculations you just use $array[$b] instead of $b.
<?php
$a = $_GET['a'];
$b = $_GET['b'];
$array = array( "option1" => 0.1,
"option2" => 0.15,
"option3" => 0.3,
"option4" => 3,
"option5" => 3,
"option6" => 16,
"option7" => 16,
"option8" => 16
);
echo "<form action='calc.php' method='get'>";
echo "<input type='text' name='a' value='".$a."'> of ";
echo "<select name='b'>";
foreach ($array as $k => $v) {
echo "<option value='".$k."'";
if ($b == $k) {
echo ' selected="selected"';
}
echo ">".$k."</option>"; // or $v if you want to show the number
}
echo "</select> ";
echo "<input type='submit' value='='> ";
$total_volume = $a * $array[$b];
echo $total_volume;
echo "</form>";
?>

Try this:
foreach ($array as $k => $v) {
$selected= ($b == $v) ? 'selected="selected"' : '';
echo "<option value='$v' $selected>$k</option>\n";
}

You have to catch the data in $_GET.
Try
foreach ($_GET as $k => $v) {
echo "<option value='".$v."'";
if ($b == $v) {
echo " selected ";
}
echo ">".$k."</option>";
}
EDIT:
On my Computer it worked here is the dump of GET
<form action='' method='get'>
<input type='text' name='a' value='121'> of <select name='b'>
<option value='0.1'>option1</option>
<option value='0.15'>option2</option>
<option value='0.3'>option3</option>
<option value='3'>option4</option>
<option value='3'>option5</option><option value='16'>option6</option><option value='16'>option7</option><option value='16'>option8</option></select> <input type='submit' value='='> 363
</form>
The Url
http://localhost/test.php?a=121&b=3
And parameters
a 121
b 3

Related

Basic PHP Array in html table

I was doing a simple PHP array table, but the result of my code is not what I've expected,
<?php
$names = array (
'First Name' =>
array('Alfre', 'Beka', 'Charlie'),
'Middle Name' =>
array('Brom', 'Tiv', 'Clore'),
'Last Name' =>
array('Adani', 'Filial', 'Chrome'),
);
echo '<table border="1">';
foreach($names as $name => $indv_name) {
echo '<tr>';
echo "<th>$name</th>";
foreach($indv_name as $per_name) {
echo '<td>',$song, '</td>';
}
echo '</tr>';
}
echo '</table>';
?>
The result of the array of this code is echoed horizontally, can anyone help me to echo it vertically?
Here's my output example:
firstname -> value, value, value
middlename -> value, value, value
lastname -> value, value, value
Output that I want to expect:
firstname - middlename - lastname
value - value - value
value - value - value
value - value - value
- value - value
- value
And whenever I add value in the array, it won't break the line.
Sorry for the late edit
A basic way
$names = array (
'First Name' =>
array('Alfre', 'Beka', 'Charlie'),
'Middle Name' =>
array('Brom', 'Tiv', 'Clore'),
'Last Name' =>
array('Adani', 'Filial', 'Chrome'),
);
echo "<table>";
echo "<thead>";
echo "<tr>";
foreach ($names as $key => $value) {
echo "<th>$key</th>";
}
echo "</tr>";
echo "</thead>";
echo "<tbody>";
foreach ($names as $key => $value) {
echo "<tr>";
foreach ($value as $key => $value) {
echo "<td>$value</td>";
}
echo "</tr>";
}
echo "</tbody>";
echo "</table>";

Generate "select inputs" through loops in arrays

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>';

Get value from array

I've following php code which store value to an Array called ch[].
echo "<input type='radio' name='ch[$roll]['$sname']['$class']' value='1' /> ";
echo "<input type='radio' name='ch[$roll]['$sname']['$class']' value='0' />";
Now I can get only $roll and value wtih following code
foreach($_POST['ch'] as $id=>$value)
{
echo "id = $id ";
echo "VAlue = $value; <br/>";
}
but I want to get the value of $sname, $class variable. Is there anyway to get these value. Can you guys give me a idea or solutions ?
Thank You.
Updated:
foreach ($_POST['ch'] as $roll => $arr1)
{
echo $roll;
foreach ($arr1 as $name => $arr2)
{
echo $name;
foreach ($arr2 as $class => $value)
{
echo $class;
echo $value;
$sql = mysql_query("INSERT INTO e_attendence VALUES('', '$sname', '$roll', '$class',
'$value', '$current_date')");
}
}
}
Give this a try
foreach ($_POST['ch'] as $roll => $arr1)
{
echo $roll;
foreach ($arr1 as $name => $arr2)
{
echo $name;
foreach ($arr2 as $class => $value)
{
echo $class;
echo $value;
}
}
}
If you are using same code as written bellow :
echo "<input type='radio' name='ch[$roll]['$sname']['$class']' value='1' /> ";
echo "<input type='radio' name='ch[$roll]['$sname']['$class']' value='0' />";
Then please remove ' from ch[$roll]['$sname']['$class'] because if you can inspect the html you will find that the radio buttons are not created properly and never use inverted commas in html input array.
After fixing this please try
echo (int)$_REQUEST['ch'][$roll][$sname][$class];
May this helps you.

PHP loop within a loop, option selected?

Using PHP I echo out table rows in a loop like this:
<?php
/* SQL STUFF */
while ($row = mysql_fetch_array($select_courseelements)) {
echo "<tr>\n";
echo "<td>".$row['scpe_name']."</td>\n";
echo "<td>".$row['scpe_days']."</td>\n";
echo "</tr>\n";
}
Now I would like to include a <select> element with 5 predefined <option> values inside a <td> running with the loop. The option values will be 1 to 5.
There is also a column inside the $row loop that holds a value of 1 to 5 ($row['scpe_grades_status']).
Each time this value is equal to the one in the <select> I want it to change it to selected='selected'.
Would this be possible?
My <select> will look something like this when it's being run in the loop:
echo "<td>\n";
echo "<select id='elements_grade'>\n";
echo "<option value='1'>Registrerad</option>\n";
echo "<option value='2'>Ej påbörjad</option>\n";
echo "<option value='3'>Pågående</option>\n";
echo "<option value='4'>Godkänd</option>\n";
echo "<option value='5'>Deltagit</option>\n";
echo "<option value='6'>Ej deltagit</option>\n";
echo "</select>\n";
echo "</td>\n";
Sure, build the values from a loop. and you can compare the values from that part.
for($i = 1; $i<=5; $i++) {
echo "<option value='$i'";
echo ($row['scpe_grades_status'] == $i) ? " selected='selected'": "";
echo ">...."</option>"
}
$array = array('Registrerad' => 1, 'Ej påbörjad' => 2, 'Pågående' => 3, 'Godkänd' => 4, 'Deltagit' => 5, 'Ej deltagit' => 6);
foreach ($array as $key=>$value) {
if ($value == $row['scpe_grades_status'])
echo '<option value="'.$value.'" selected>'.$key.'</option>';
else
echo '<option value="'.$value.'">'.$key.'</option>';
}
Something like that?

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