been trying to figure out the best way to do something. I have the following
$inputParams = array();
if (isset($_POST["inputOne"]) && !empty($_POST["inputOne"])) {
$inputOne = $_POST["inputOne"];
array_push($inputParams, $inputOne);
}
if (isset($_POST["inputTwo"]) && !empty($_POST["inputTwo"])) {
$inputTwo= $_POST["inputTwo"];
array_push($inputParams, $inputTwo);
}
if (isset($_POST["inputThree"]) && !empty($_POST["inputThree"])) {
$inputThree= $_POST["inputThree"];
array_push($inputParams, $inputThree);
}
So, because not all the inputs are required, my array could have 1, 2 or 3 values.
I then come to the part that handles the array, at the moment I have something like
$this->inputOne = $inputParams[0];
$this->inputTwo = $inputParams[1];
$this->inputThree = $inputParams[2];
Obviously this is not a good way to do it, because if one of the inputs is empty (which they can be) then the above will throw an error. I need to assign the values to a variable if they exist though, so what would be the best way to do this? I was thinking a foreach loop, but then I dont know how much control I have over the value being assigned (if only inputOne and inputThree have data, will inputThree be assigned to variable 2?)
UPDATE
If I have
$this->inputOne = (!empty($inputParams[0])) ? $inputParams[0] : 'no data';
$this->inputTwo = (!empty($inputParams[1])) ? $inputParams[1] : 'no data';
$this->inputThree = (!empty($inputParams[2])) ? $inputParams[2] : 'no data';
var_dump("Input One is " . $this->email);
var_dump("Input Two is " .$this->mobNumber);
var_dump("Input Three is " .$this->storeCode);
And I fill in the fields inputOne and inputThree (giving the second one no data), then the output is
string(37) "Input One is myemail#gmail.com"
string(19) "Input Two is ABC123"
string(22) "Input Three is no data"
So the data from input three has been given to input two. Is there any way to stop this happening?
You can user ternary operator to check if variables are empty and assign.
Ofocurse this is for only if you know the number of elements in the array else ARRAY is your best friend
$this->inputOne = (!empty($inputParams[0])) ? $inputParams[0] : '';
$this->inputTwo = (!empty($inputParams[1])) ? $inputParams[1] : '';
$this->inputThree = (!empty($inputParams[2])) ? $inputParams[2] : '';
UPDATE:
You can loop through the $this object and check for properties which has value 'no data' and remove those properties.
foreach ($objects as $key => $value) {
if($objects->key == 'no data'){
unset($objects->key); // This will just remove that property.
}
}
If you have an unknown number of input values, then don't work with separate variables and fields for each, but use arrays all the way through:
<input name="input[]">
<input name="input[]">
<input name="input[]">
<?php
if ($_POST) {
$this->inputs = array_filter($_POST['input']);
}
That's all you need. Gives you an array with as many input values as you got, with empty elements filtered out.
Just for example:
if (isset($_POST["inputThree"]) && !empty($_POST["inputThree"])) {
$inputThree= $_POST["inputThree"];
}
else {
$inputThree = 0; //or some value which you want
}
array_push($inputParams, $inputThree);
Instead of passing the input elements as inputOne, inputTwo and inputThree, pass the data as array using JSON object and parse it back here so you can put these in a loop and process this data in a more elegant way.
Refer for JSON.stringify here : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
Refer for json_decode here :
http://php.net/manual/en/function.json-decode.php
Once you have decoded it you can process it as an array like
$inputParams = array();
$inputElems = json_decode($_POST['input_arr']);
foreach($inputElems as $Elem)
{
if (isset($Elem) && !empty($Elem)) {
array_push($inputParams, $Elem);
}
Related
I will be getting some certain amount of data. I will get the number for which the for loop to be run.
For example
I get the number 3 and I will get three parameters like par1,par2 and par3 then how should I pass this par1 in the $_post
like
$i=$_POST["number"];
for($i=1;$i<=$n;$i++)
{
$par.$i = $_POST["par".$i];
}
Here I cant get the value from $_POST["par".$i];
As it is not able to get the variable inside the paramater of $_POST
Any help will be thankful
I suggest that you create a new array $par and there you will put by index all the par you will have like this:
$i=$_POST["number"];
$par = [];
for($i=1;$i<=$n;$i++)
{
$par[$i] = $_POST["par".$i];
}
After that if you want to go throw all pars you can simply use foreach like this:
foreach($par as $key => $value) {
// $key will be 1,2,3
// $value will be the value from $_POST["par" . $i]
}
The . is to concatenate two strings in PHP, and you can't create a new variable like you tried. If you want to have in $par1, $par2 and $par3 you can do like this:
${"par" . $i} = $_POST["par".$i];
But I don't recommend this way because it's more hard to handle.
One Way
According to your question.
<?php
$n = $_POST["number"];
$par = "par";
for($i=1; $i<=$n; $i++){
$par.$i = $_POST["par".$i];
}?>
Alternative Way
In this scenario,
For example I get the number 3 and I will get three parameters like
par1,par2 and par3 then how should I pass this par1 in the $_post.
Better, make 'par' input name as an array type as 'par[]' (<input type='text' name='par[]'>) in your file instead using par1, par2 .. par(n).
And, no need to worry in submit page.
<?php
$n = $_POST["number"];
for($i=1;$i<= $n;$i++){
$newPar = $_POST["par"][$i];
// Write here your logic to use how you want.
}
?>
So I know how to error check an empty post value with an if empty combination, however how can this be done if the post data is an array and it needs to be applied to each value?
Example:
foreach (array($_POST['post_values']) as $test) {print_r($test); echo'<br />';};
where
<input name="post_values[value_1]">
<input name="post_values[value_2]"> etc.
I need to be able to say that if a value is not posted to any of the inputs, then that particular input = zero without applying a default value to the inputs themselves.
Therefore if value_1 = 5 and value_2 = blank, the array will show as 5 and 0.
Thanks in advance,
Dan
You can do something like this:
for ($i = 0; $i < count($_POST['post_values']); $i++){
if (empty($_POST['post_values'][$i])){
$_POST['post_values'][$i] = 0;
}
}
Would this work?
foreach ($_POST['post_values'] as $key=>$test) {
if($test==""){
$_POST["post_values"][$key]=0;
}
};
print_r($_POST['post_values']);
you can do the following. inside your look you can check for value
$value = (trim($test) != "" ? $test : 0);
echo $value; // if $test is blank then it would be 0 else would get value of $test.
Usually when I use PHP I create a variable and post statement for each form input like so:
$myVar1 = $_POST["formItem1"];
$myVar2 = $_POST["formItem2"];
ect......
I know if i use:
echo $_POST;
I can get all the key and values from the form inputs but I don't know how to use them in a script.
So I guess I have 2 questions:
How do I quickly post all form inputs without creating a variable for each input?
How do I use a posted in a script without having it assigned to a specific variable?
To simply echo all the inputs, you can use a foreach loop:
foreach ($_POST as $key => $value) {
echo $value.'<br/>';
}
If you don't want to store them in variables, use arrays:
$data = array();
foreach ($_POST as $key => $value) {
$data[] = $value;
}
Now, $data is an array containing all the data in $_POST array. You can use it however you wish.
You don't have to assign to a variable. You can use directly $_POST['input_name']
If you want to deal with each sended params, you can use foreach loop:
foreach ($_POST as $key => $val)
{
echo "$key : $val <br/>";
}
for this instance of just quickly checking and testing i typically just use the print_r() function: documentation here
as quoted from the docs:
print_r() displays information about a variable in a way that's readable by humans.
one line easy to toggle on and off (with comments)- no need to use any form of variables
print_r($_POST);
if i need my output nice and readable i like to expand it as follows:
function print_r2($x){
echo '<pre>';
print_r($x);
echo '</pre>';
}
and then you can call with: print_r2($_POST);
this way you get the pre-formatted text block on your html page and can see the line breaks and tabbed spacing provided from the $_POST object printout
Another way to extract (besides the extract function) variables is;
$array = array('foo'); // Which POST variables do you want to get
foreach($array as $key) {
if(!isset(${$key})) { // Check if variable hasn't been assigned already
${$key} = $_POST[$key];
}
}
echo $foo;
I would not recommend it because it can get quite messy to keep up.
View everything in $_POST is useful for debugging
echo '<pre>'.print_r($_POST, true).'</pre>';
Access a specific checkbox
HTML
<input type="checkbox" value="something" name="ckbox[]" checked>
<input type="checkbox" value="anotherthing" name="ckbox[]" checked>
PHP
echo $_POST['ckbox'][0]; // something
echo $_POST['ckbox'][1]; // anotherthing
// isolate checkbox array
$ckbox_array = $_POST['ckbox'];
Define a function that allows you to access a specific $_POST item by name (key):
function get_post_value($name, $default)
{
if ( isset($_POST[$name]) ) {
return $_POST[$name];
} else if ( $default ) {
return $default;
}
return null;
}
$default allows you to pass a value that can be used as a fallback if the key you specify isn't present in the $_POST array.
Now you can reference $_POST items without assigning them to a variable, and without worrying if they are set. For example:
if ( get_post_value('user-login-submit', false) ) {
// attempt to log in user
}
You can use extract($_POST), it will create variables for you.
For example, you can have for the code you posted :
<?php
$_POST["formItem1"] = "foo";
extract($_POST);
echo $formItem1; // will display "foo"
?>
EDIT : it's not PHP explode, it's extract.
I post some data over to another page from a form. It's a shopping cart, and the form that's being submitted is being generated on the page before depending on how many items are in the cart. For example, if there's only 1 items then we only have the field name 'item_name_1' which should store a value like "Sticker" and 'item_price_1' which stores the price of that item. But if someone has 5 items, we would need 'item_name_2', 'item_name_3', etc. to get the values for each item up to the fifth one.
What would be the best way to loop through those items to get the values?
Here's what I have, which obviously isn't working.
extract($_POST);
$x = 1; // Assuming there's always one item we're on this page, we set the variable to get into the loop
while(${'item_name_' .$x} != '') {
echo ${'item_name' .$x};
$x++;
}
I'm still relatively new to this kind of usage, so I'm not entirely how the best way to deal with it.
Thanks.
First, please do not use extract(), it can be a security problem because it is easy to manipulate POST parameters
In addition, you don't have to use variable variable names (that sounds odd), instead:
foreach($_POST as $key => $value) {
echo "POST parameter '$key' has '$value'";
}
To ensure that you have only parameters beginning with 'item_name' you can check it like so:
$param_name = 'item_name';
if(substr($key, 0, strlen($param_name)) == $param_name) {
// do something
}
Use array-like fields:
<input name="name_for_the_items[]"/>
You can loop through the fields:
foreach($_POST['name_for_the_items'] as $item)
{
//do something with $item
}
If your post keys have to be parsed and the keys are sequences with data, you can try this:
Post data example: Storeitem|14=data14
foreach($_POST as $key => $value){
$key=Filterdata($key); $value=Filterdata($value);
echo($key."=".$value."<br>");
}
then you can use strpos to isolate the end of the key separating the number from the key.
i wouldn't do it this way
I'd use name arrays in the form elements
so i'd get the layout
$_POST['field'][0]['name'] = 'value';
$_POST['field'][0]['price'] = 'value';
$_POST['field'][1]['name'] = 'value';
$_POST['field'][1]['price'] = 'value';
then you could do an array slice to get the amount you need
If i send four POST variables, but the second one — I dont know that the name="" tag will be; how can I access it? Can i use $_POST[1] or not?
Here's one solution using internal pointers:
if(count($_POST) > 1){ // just a check here.
reset($_POST); // reset the pointer regardless of its position
$second_value = next($_POST); // get the next value, aka 2nd element.
}
By the way with regards to the numeric index: PHP $_POST and $_GET are associative arrays! They do not support something like $_POST[0] or $_POST[1]. They will return NULL because they are not set. Instead $_POST["name"] would work.
From the PHP Manual: "An associative array of variables passed to the current script via the HTTP POST (or GET) method."
i have a handy function for this
function nth($ary, $n) {
$b = array_slice($ary, intval($n), 1);
return count($b) ? reset($b) : null;
}
in your case
$foo = nth($_POST, 1);
foreach( $_POST as $key => $value ){
if( is_int($key) ) //do something with $value
}
This will work if you know the other $_POST values have names in your forms (i.e., keys that aren't numbers).
You can loop through it:
foreach ($_POST as $k => $v) {
if (substr($k, 0, 3) == 'id_') {
// do stuff
}
}
But it really depends on what the criteria for the search is. In the above example it's pulling all the POST variables that start with "id_". You may be able to do it simpler if you have a different/better criteria.
You can if you convert it using array_values() first.
Example
<?php
$a = array(
"first key" => "first value",
"second key" => "second value",
);
$v = array_values($a);
echo "First value: {$v[0]}\n";
?>
Output
$ php -f a.php
First value: first value
EDIT: Thanks for commentators pointing out the initial error.
use
<?php
print_r($_POST);
?>
this will give you an idea of what is the key of the field you don't know.
Make a copy :
$vars = $_POST;
Remove the names you know :
unset( $vars[ "known variable 1" ] );
unset( $vars[ "known variable 2" ] );
All that remains is the variables you need : extract them with array_values or enumerate them with foreach, whatever.
a simple for each will do the trick if you do not know the array keys on the $_POST array
foreach($_POST as $key=>$value):
print 'key'.$key.' value'.$value
endforeach;
But it is recommended to know what your post variables are if you are planning on processing them.