multi-dimensional array from forminput - php

I think my solution is in a multi-dimensional array, but how...
If i have the following (or similar) in a HTML form (simplified for example)
<select name="Postage[]" id="Unique-ID">
<option value="1">Postage Option 1</option>
<option value="2">Postage Option 2</option>
<option value="3">Postage Option 3</option>
</select>
<input name="PostagePrice[]" id="Price-Unique-ID" value="" />
<select name="Postage[]" id="Unique-ID">
<option value="1">Other Postage Option 1</option>
<option value="2">Other Postage Option 2</option>
<option value="3">Other Postage Option 3</option>
</select>
<input name="PostagePrice[]" id="Price-Unique-ID" value="" />
<select name="Postage[]" id="Unique-ID">
<option value="1">Another Postage Option 1</option>
<option value="2">Another Postage Option 2</option>
<option value="3">Another Postage Option 3</option>
</select>
<input name="PostagePrice[]" id="Price-Unique-ID" value="" />
How do i get this stored into a PHP array (so i can later add it to my DB)
So far i have the below, but it is clearly not finnished
if (isset($_POST['Postage'])) {
if (is_array($_POST['Postage'])) {
foreach($_POST['Postage'] as $PostateID=>$PostageOption){
// this is where i am tottally stuck
// need to assosiate postageID with a Postage Option and a PostagePrice
}
}
}
Im sorry to sound dumb but i have not yet had the "Erika" moment with multi-dimensional array's
I would be grateful for any advice

$_POST['Postage'] is not a multidimensional array. You can easily see it if you var_dump($_POST['Postage']); It's just an array of all the selected indexes in your selects:
array(3) {
[0]=>
string(1) "1"
[1]=>
string(3) "1"
[2]=>
string(3) "1"
}
Here is what I input for testing:
And here I get the postages and associated prices, using a for loop:
<?php
$n = count($_POST['Postage']);
for ($i = 0; $i < $n; ++$i)
{
print $_POST['Postage'][$i] . " " . $_POST['PostagePrice'][$i] . "<br>";
}
prints:
1 1
2 2
2 3

Consider your array of inputs as below:
<?
//Let your inputs be Postage1, Price1, Postage2, Price2...
//Then your Received POST will be..
$_POST = Array(
"Postage" => Array( 0 => 'Postage1', 1 => 'Postage2', 2 => 'Postage3'),
"PostagePrice"=> Array( 0 => 'Price1', 2 => 'Price2', 3 => 'Price3')
);
//Now, you can see that index 0 points to a price of POSTAGE and so on 1 and 2..
//Store corresponding values in an Array.
$store = Array();
foreach($_POST['Postage'] as $PostateID=>$PostageOption){
$store[$PostageOption] = $_POST['PostagePrice'][$PostateID];
}
print_r($store);
?>

<?PHP
$final = array_combine($_POST['Postage'], $_POST['PostagePrice']);
?>
By this way, you will associate Postage and PostagePrice in this array.

Related

PHP : Get Multi Select Box value as comma separated value

Hi I have a multi select box as below
HTML
<form action="c3.php" method="post">
<select name="ary[]" multiple="multiple">
<option value="Option 1" >Option 1</option>
<option value="Option 2">Option 2</option>
<option value="Option 3">Option 3</option>
<option value="Option 4">Option 4</option>
<option value="Option 5">Option 5</option>
</select>
<input type="submit">
</form>
I need to get the values selected by user as comma separated.
eg. if user selects Option1 and Option4 I need to read that as Option1,Option4
if he is selecting Option1 only .It should return as Option1 (no comma)
I have a code like this
PHP
foreach ($ary as $a){
//echo $a;
$com_values = implode(",", array_filter([$a])) ;
}
but the above php code is giving me only one value it is not giving me comma separated values /Any issues ?
You need to implode on the actual array, looping over the array is only going to give you the one value in the loop.
$com_values = implode(",", $_POST["ary"]);
Should give you what you need.

how to echo text not value

I am attempting to echo the name of a selected dropdown rather than its value. I understand that echoing a dropdown's value can be achieved by implementing something such as:
$no2 = $_POST['vehicleStyle'];
echo $no2;
where vehicleStyle is the name.
this is my code
<select name="vehicleStyle">
<option value="2">Volvo</option>
<option value="3">Saab</option>
<option value="4">Fiat</option>
<option value="5">Audi</option>
</select>
If I add
$no2 = $_POST['vehicleStyle'];
echo $no2;
to my code, I get either 2,3,4 or 5 (whichever is selected). How can I echo the dropdown name, either volvo, saab , fiat or audi?
NOTE: i use this code
$no2 = $_POST['vehicleStyle'];
echo $no2;
to show the price of the car which i set in value, but also i need to echo the text to show the name of the car, how i can do that?
if you don't need the values (2, 3, 4, 5), you can just use:
<select name="vehicleStyle">
<option>Volvo</option>
<option>Saab</option>
<option>Fiat</option>
<option>Audi</option>
</select>
but if you need both, you should do something like this:
$no2 = [
"2" => "Volvo",
"3" => "Saab",
"4" => "Fiat",
"5" => "Audi"
]$_POST['vehicleStyle'];
echo $no2;
be aware that if you change the dropdown in the future, you have to come back here and change also this array
Simple approach is give the value the same as the text in it!
<form method="post">
<select name="vehicleStyle">
<option value="Volvo">Volvo</option>
<option value="Saab">Saab</option>
<option value="Fiat">Fiat</option>
<option value="Audi">Audi</option>
</select>
<input type="submit" name="vehicleName">
</form>
if(isset($_POST['vehicleName'])){
echo $_POST['vehicleStyle'];
}
If you are also need both text(name) and value(id) as magnus eriksson Suggest you need to separate them like: id;name and explode it on the back end to get id as well as name.
<form method="post">
<select name="vehicleStyle">
<option value="2;Volvo">Volvo</option>
<option value="3;Saab">Saab</option>
<option value="4;Fiat">Fiat</option>
<option value="5;Audi">Audi</option>
</select>
<input type="submit" name="vehicleName">
</form>
if(isset($_POST['vehicleName'])){
list($id, $name) = explode(';', $_POST['vehicleStyle']);
echo $id.' => '.$name;
}
Thank you all,
i solved this by editing the code to:
<form method="post">
<select name="vehicleName">
<option value="2|volvo">Volvo</option>
<option value="3|saab">Saab</option>
<option value="4|fiat">Fiat</option>
<option value="5|audi">Audi</option>
</select>
<input type="submit" name="submit">
</form>
and
if(isset($_POST['submit']))
{
$no2=$_POST['vehicleName'];
$no2_explode=explode('|', $no2);
for text
<?php echo $no2_explode[1]; ?>
and for the price number
<?php echo $no2_explode[0]; ?>

php - multiple select with different values (security easier method)

I don't think this is a duplicate, I only found fairly similar questions.
I have 4 checkboxes and I want to make sure they are different, but I think my "if" is a mess. Let's imagine I have 20 select boxes, then I'd have an endless "if" (option1!=option2...option20, it'd be a really long "if").
How can I simplify this? A while loop or something?
Here is what I have:
PHP check it, then save it:
if(($option1!=$option2 and $option1!=$option3 and $option1!=$option4)
and ($option2!=$option1 and $option2!=$option3 and $option2!=$option4)
and ($option3!=$option1 and $option3!=$option2 and $option3!=$option4)
and ($option4!=$option1 and $option4!=$option2 and $option4!=$option3)) {
//insert it to database if everything is okay...
HTML:
<select name="option1">
<option value="">Choose one</option>
<option value="1">Option A</option>
<option value="2">Option B</option>
<option value="3">Option C</option>
<option value="4">Option D</option>
...
</select>
<select name="option2">
<option value="">Choose one</option>
<option value="1">Option A</option>
<option value="2">Option B</option>
<option value="3">Option C</option>
<option value="4">Option D</option>
...
</select>
<select name="option3">
<option value="">Choose one</option>
<option value="1">Option A</option>
<option value="2">Option B</option>
<option value="3">Option C</option>
<option value="4">Option D</option>
...
</select>
<select name="option4">
<option value="">Choose one</option>
<option value="1">Option A</option>
<option value="2">Option B</option>
<option value="3">Option C</option>
<option value="4">Option D</option>
...
</select>
If you have 20 select dropdown lists with all of them have name attributes in chronological order, like name='option1', name='option2', ... , name='option20', then you should use a for loop like this:
$numSelects = 20;
$selectValues = array();
$differentValues = true;
for($i = 1; $i <= $numSelects; ++$i){
if(in_array($_POST['option'.$i], $selectValues)){
$differentValues = false;
break;
}
$selectValues[] = $_POST['option'.$i];
}
if($differentValues){
// all the selected values are different
}else{
// selected values are not different
}
$numSelects is the number of select dropdown lists in your code, so you need to change this value as per your code. And what this for loop here does is, in each iteration of for loop it checks whether the user's selected value exists in $selectValues array or not, and if the value already exists in the array then it will disable $differentValues flag and break out from the loop. Moreover, in each iteration it appends user's selected value to $selectValues array. After coming out of the loop, you can check whether all submitted values are different or not, based on the status of $differentValues flag.
You could do it like this using array_unique(), you could build on it to know which key is missing to show an error in the right place. It also allows you to define which post keys your expecting to check/count.
<?php
$_POST = [
'name' => 'Steve McQueen',
'csrf' => 'y53zmSV0LhhjcjEg',
'option1' => '1',
'option2' => '3',
'option3' => '2',
'option4' => '1'
];
$expected = [
"option1",
"option2",
"option3",
"option4"
];
$result = [];
foreach ($expected as $key) {
$result[$key] = isset($_POST[$key]) ? $_POST[$key] : null;
}
$check = array_unique($result);
if (count($check) !== count($expected)) {
echo 'Please only select unique choices from the options';
} else {
echo 'All good!';
}

walking through php array

Can anyone point me in the right direction with the below
I have this HTML in a FROM (simplified for this example):
=============== Start HTML ===================
<select name="Postage[]" id="Unique-ID">
<option value="1">Postage Option 1</option>
<option value="2">Postage Option 2</option>
<option value="3">Postage Option 3</option>
</select>
<input name="PostagePrice[]" id="Price-Unique-ID" value="" />
<select name="Postage[]" id="Unique-ID">
<option value="1">Postage Option 1</option>
<option value="2">Postage Option 2</option>
<option value="3">Postage Option 3</option>
</select>
<input name="PostagePrice[]" id="Price-Unique-ID" value="" />
<select name="Postage[]" id="Unique-ID">
<option value="1">Postage Option 1</option>
<option value="2">Postage Option 2</option>
<option value="3">Postage Option 3</option>
</select>
<input name="PostagePrice[]" id="Price-Unique-ID" value="" />
================== End HTML =====================
I am collecting this from the form and setting it to an array ($arrPostageOptions) with the below code:
=============== Start PHP ===================
if (isset($_POST['Postage'])) {
if (is_array($_POST['Postage'])) {
$n = count($_POST['Postage']);
for ($i = 0; $i < $n; ++$i) {
// check to only collect completed entries
if( !empty($_POST['Postage'][$i]) && !empty($_POST['PostagePrice'][$i]) ){
// assign to array
$arrPostageOptions[$i] = array( "Postage" => $_POST['Postage'][$i], "PostagePrice" => $_POST['PostagePrice'][$i], );
}
}
}
}
=============== End PHP ===================
This results in the following array
============ array result ===============
Array(
[0] => Array
(
[Postage] => 1
[PostagePrice] => 12
)
[1] => Array
(
[Postage] => 2
[PostagePrice] => 24
)
[2] => Array
(
[Postage] => 3
[PostagePrice] => 48
)
)
============ end array result ===============
The answer (I think) I want is for each array is :
1 & 12
2 & 24
3 & 48
(that the array numbers match the postage numbers is just coincidence, I only want ‘Postage’ and ‘PostagePrice’)
I am trying the following:
=========== start of what I am trying ==========
foreach ($arrPostageOptions as $id) {
while ($id) {
$Postage = $id["Postage"];
$PostagePrice = $id["PostagePrice"];
// echo $Postage.' '.$PostagePrice.'<br>';
unset($id);
if (!$listing_obj->addPostageOptions($ListingID, $PostageOptionID, $PostagePrice, $db)) {
$err_text .= 'An error occurred adding Postage Option'.$PostageOptionID;
}
}
}
====== end of what I am trying ==============
Unfortunately this is not working as I expect (but is the closest I have gotten) . I have also tried multiple foreach loops, but again I don’t get what im after
(unsettling the $id is stopping the loop from continuing for ever, but is also giving me PHP notices of Undefined variable $id)
I’m sure I know how to do this, but seem to have forgotten and have possible over complicated it as these arrays are still confusing the s**t out of me.
Any advice would be greatly welcomed!
Why not simply:
foreach ($arrPostageOptions as $postageOption) {
$postage = $postageOption["Postage"];
$postagePrice = $postageOption["PostagePrice"];
echo $postage.' '.$postagePrice.'<br>';
...
}
Sorry for renaming, but $id was too confusing for me.
I'm not entirely sure I understood what you want to do but it would seem to me that you want to iterate the array like this, but I'm not sure.
foreach ($arrPostageOptions as $id=>$array) {
foreach($array as $key=>$val){
// do your stuff here using where you can also reference $id
}
}
there are a couple of things I would like to say is that the isset function is a bit pointless here and it is best used along with a submit button, not for text fields and other inputs.
Also, you are declaring your array inside the loop so accessing it anywhere outside will give an undefined error.
I just used your form and updated the php script slightly to give the output you desire. Please have a look.
Your form
<form action="yourscript.php" method="POST">
<select name="Postage[]" id="Unique-ID">
<option value="1">Postage Option 1</option>
<option value="2">Postage Option 2</option>
<option value="3">Postage Option 3</option>
</select>
<input name="PostagePrice[]" id="Price-Unique-ID" value="" />
<select name="Postage[]" id="Unique-ID">
<option value="1">Postage Option 1</option>
<option value="2">Postage Option 2</option>
<option value="3">Postage Option 3</option>
</select>
<input name="PostagePrice[]" id="Price-Unique-ID" value="" />
<select name="Postage[]" id="Unique-ID">
<option value="1">Postage Option 1</option>
<option value="2">Postage Option 2</option>
<option value="3">Postage Option 3</option>
</select>
<input name="PostagePrice[]" id="Price-Unique-ID" value="" />
<input type="submit" value="submit" name="submit"/>
</form>
I added a submit button and a the method and action in the header just to make it a bit more clear.
And here is the script I used, pretty similar to yours
<?php
$arrPostageOptions = array();
if(isset($_POST['submit']))
{
$postage = $_POST['Postage'];
$postagePrice = $_POST['PostagePrice'];
$array_size = count($postage);
for($i = 0; $i < $array_size; $i++)
{
if(!empty($postage[$i]) && !empty($postagePrice[$i]))
{
$arrPostageOptions[$i] = array("Postage"=>$postage[$i],
"PostagePrice"=>$postagePrice[$i]);
}
}
print_r($arrPostageOptions);
}
?>
I check if the submit button is set/clicked and enter the loop. I define the array variable outside so it can be used anywhere in the program.
If you see the print_r result, you will see the array in the format you desire.
I hope I answered a couple of your questions.
At the same time, its better to always put your POST data into variables before using them so you can check them and control them better than directly using $_POST['name']. This will be of more use when you work with databases and other related things.
Hope this helps.
Thanks,
Shawn.
The while within the foreach is redundant. foreach will only continue as long as there is a new entry to become $id anyhow.
The loop should be fine if you remove the while. If you want to test whether the data is valid, test on the array keys themselves like by putting this in the loop
if(!$id["Postage"] || !$id["PostagePrice"]){
continue;
}

PHP issue with Dropdown list

I have created a populated dropdown list in HTML. When the two dropdowns have been selected, the form posts to 'calculate.php' where the php script echoes out the selected values from the dropdowns.
<form action="calculate.php" method='POST'>
<select name="Phones">
<option value="Lumia800">Nokia Lumia 800</option>
<option value="iPhone">Apple iPhone 4s</option>
<option value="GalaxyS2">Samsung Galaxy S2</option>
<option value="Bold9900">Blackberry Bold 9900</option>
<option value="SensationXE">HTC Sensation XE</option>
<option value="XperiaS">Sony Ericsson Xperia S</option>
</select>
<select name="Network">
<option value="Orange">Orange</option>
<option value="Vodafone">Vodafone</option>
<option value="O2">O2</option>
<option value="Three">Three</option>
</select>
<input type="submit" />
</form>
In this one example, 'calculate.php' echoes the selected dropdown values.
<?php
$pref=$_POST['Phones'];
$pref1=$_POST['Network'];
$Orange="5";
if ($pref1 == "Orange")
{
$total1 = $Orange;
}
$Lumia800="10";
if ($pref == "Lumia800")
{
$total = $Lumia800 + $Orange;
}
echo $total;
?>
This example output is '15'
The aim of this example is to eventually create a simple phone package system, with this set of code adding the price of the phone, the network costs, and other variables together for a final total of how much it would cost when the user submits it.
The problem I have is that I want to add each variable from the corresponding dropdown boxes ("Phones" and "Network" for example) against each other. Is my example going to be too over complicated for such a simple script? Is there a more refined method to get the results that I want?
Thanks,
JB.
You should define arrays for each select that contains all prices.
$phone_prices = array("Lumia800" => 10, "iPhone" => 42);
$network_prices = array("Orange" => 5, ...);
And then you coud simply do something like
$price = $phone_prices[$pref] + $network_prices[$pref1];
But this is not really safe, make sure $pref and $pref1 are existing indexes in their respective array.
It will work but might be complicated. I would suggest changing over to a switch statement instead.
$total = 0
switch ($pref) {
case "Orange":
$total += 5;
break;
case "O2":
$total += 8;
break;
}
Same switch structure would be for the $pref1 or network variable.
<form action="calculate.php" method='POST'>
<select name="Phones">
<option value="123">Nokia Lumia 800</option>
<option value="234">Apple iPhone 4s</option>
<option value="12">Samsung Galaxy S2</option>
<option value="32">Blackberry Bold 9900</option>
<option value="432">HTC Sensation XE</option>
<option value="12">Sony Ericsson Xperia S</option>
</select>
<select name="Network">
<option value="42">Orange</option>
<option value="34">Vodafone</option>
<option value="23">O2</option>
<option value="34">Three</option>
</select>
<input type="submit" />
</form>
and
<?php
echo $_POST['Network'] + $_POST['Phones'];
?>
might be a lot simpler in that case, but that of course depends on the exact situation where you need this.
G'day mate.
You could for one, create an array of mapping from Phones => Price and Network => Price
example:
<?php
$phones = array(
'Lumia800' => 10,
'iPhone' => 15,
'GalaxyS2' => 30,
// rest of the phones with price
);
$networks = array(
'Orange' => 10,
'Vodafone' => 15,
'Three' => 3,
'O2' => 8
);
then validate user input
if(!empty($phones[$pref])) && !empty($networks[$pref1])) {
echo $phones[$pref] + $networks[$pref1];
}
If your code isn't going to be more complicated then what i see now
I would just change:
...
<option value="iPhone">Apple iPhone 4s</option>
...
<option value="Orange">Orange</option>
...
to
...
<option value="5">Apple iPhone 4s</option>
...
<option value="10">Orange</option>
...
And then loop all the values at the end
$total = 0;
foreach ($_POST as $key => $val) {
$total += $val;
}
echo $total;
That way you can change the amount of dropdowns

Categories