Use $_POST values by number - php

i'm not sure how to explain it correctly, but i would like to use $_POST values like this $_POST[0] and not like this $_POST['form_field_name'].
Let's say i have 3 form fields so if i'd like to get data from post like this:
echo $_POST[0];
echo $_POST[1];
echo $_POST[2];
I hope you guys understand what i wanna do here.

Try it like this:
$values = array_values($_POST);
No idea why you would do such a thing though.

I would not recommend ever to refer to your $_POST values with indexes, as it is generally a bad idea.
You can access them by indexes if you do this:
$items = array_values($_POST);
$foo = $items[0];
$bar = $items[1]
You can also run through your values with a foreach loop, like this (which is better, but still bad!)
foreach($_POST as $item)
{
// do your thing here
}

$_POSTs variables depends on the name attribute of the form element as you can read in this link.
On the other hand the attribute name of the form elements according to W3C always must begin with a letter.
But I think you can prepare the $_POST variable before all your code (at the begining of your php script) with:
$arrPostVariables = array_values($_POST);
And then call them in the way as you want, but I think you will previously must detect the order of the array in order to avoid errors by not having the text of each variable.

This should work:
<input name="0" value="val0" />
<input name="1" value="val1" />

Related

How to put textbox value into array only if it has value?

I have created many textboxes and I want to put all of the values into array only if they have themselves filled. I need them to work as how checkbox works in HTML (only the checked ones will then put into array). I use PHP language here. How to do that?
This is my simple HTML textbox:
<input name="array[]">
Would really appreciate for any help you give to me. Much thanks!
Firstly, I'd recommend you change your name to something more readable:
<input name="name[]">
Next, you want to get your data, I am assuming your form is using POST. We're going to store the form data into a $names array variable.
$names = $_POST['name'];
Next, we're going to create a new array variable which will store input values that have data.
$namesWithData = [];
We're now going to loop through the $names array. This loop will add any fields with data to the $namesWithData array.
foreach($names as $name) {
if(!empty($name) {
array_push($namesWithData, $name);
}
}
The $namesWithData array has the data ready to use.

How to get value of an associative HTML array in PHP using a string?

Look I have a form like this:
<form method="post">
<input name="variable[var1][var2]" value="44"/>
</form>
I want to get the value of variable[var1][var2] in PHP using a string like:
$str = "['variable']['var1']['var2']";
echo "{$_POST{$str}}";
Why I need to do that?
I need it because the code that gets the value is totally dynamic and I cannot get or set manually the value using $_POST['variable']['var1']['var2'].
Can you help?
NOTE: I know this is possible to get it using $_POST['variable']['var1']['var2'], please don't ask me about why I'm not using this way. Simply I need to use as above (using $str).
You can use preg_match_all() to get all the indexes in the string into an array:
$indexes = preg_match_all('/(?<=\[\')(?:[^\']*)(?=\'\])/', $str);
$indexes = $indexes[0]; // Get just the whole matches
Then use a loop to drill into $_POST.
$cur = $_POST;
foreach ($indexes as $index) {
$cur = $cur[$index];
}
At this point $cur will contain the value you want.
You're WAY overthinking it. Anything you put in [] array notation in a form field's name will just become an array key. The following is LITERALLY all you need:
<input name="foo[bar][baz][qux]" ... />
$val = $_POST['foo']['bar']['baz']['qux'];
You cannot use a string as an "address" into the array, not without insanely ugly hacks like eval, or parsing the string and doing a loop to dig into the array.
It's hard to believe that this is a requirement. If you could expand more on what you're trying to achieve, someone undoubtedly has a better solution. However, I will ignore the eval = evil haters.
To echo:
eval("echo \$_POST$str;");
To assign to a variable:
eval("\$result = \$_POST$str;");
If you're open to another syntax then check How to write getter/setter to access multi-level array by key names?

How get size_of $_GET

I want to get the number of values that were submitted via my $_GET. I'm going to be using a for loop and every 7 are going to be saved to a class. Does anyone know how to find the Size_of the $_GET array? I looked through this info $_GET Manual, but don't see what I'm looking for.
This is a code snippet that I started in the class that I go to after the submit.
for($i=0;$i<$_GET<size>;$i++) {
$ID = $_GET["ID"][$i];
$Desc = $_GET["Desc"][$i];
$Yevaluation = $_GET["Yevaluation"][$i];
$Mevaluation = $_GET["Mevaluation"][$i];
$Cevaluation = $_GET["Cevaluation"][$i];
$Kevaluation = $_GET["Kevaluation"][$i];
$comment = $_GET["comment"][$i];
//saving bunch to class next
}
$_GET is an array. Like any other array in PHP, to find the number of elements in an array you can use count() or its alias sizeof().
count($_GET["ID"])
could work. However, then you have to be sure that each index contains the same number of elements.
More secure would be
min(count($_GET["ID"]), count($_GET["Desc"]), ...)
With array_map this can probably be shortcut to something like:
min(array_map(count, $_GET))
Try thinking through the last one, if it seems difficult to you. It's called functional programming and it's an awesome way to shortcut some stuff. In fact array_map calls another function on each element of an array. It's actually the same as:
$filteredGet = array();
foreach ($element in $_GET) { // this is the array_map part
$filteredGet[] = count($element);
}
min($filteredGet);
Even better would be a structure where $i is the first level of the array, but I think this is not possible (built-in) with PHPs $_GET-parsing.

Simple syntax issue with $_POST

I want to concatenate a variable within the $_POST[] brackets for a while loop. My question is, is it possible. Here is the code.
$m=0;
$_POST['tier_' . $m];
Yes. However your form should probably be more like:
<input type="text" name="tier[]" />
Then $_POST['tier'] will be an array you can loop through.
It is possible, yes, but the code sample you provided would cause a notice because it would try to check an index that does not yet exist. The following would work:
$m=0;
$_POST['tier_' . $m] = 'something';

PHP Variables made with foreach

I have several variables coming from an array in $POST_['array'] i wish to make some kind of loop for example foreach that makes, for every value in the variable a variable name of it and assigns the value for it.
For example if i have
$POST_['name'];
$POST_['last'];
$POST_['age'];
$POST_['sex'];
I want the loop to create each variable from the array inside the $_POST with the name of the variable like the following:
$name = 'John';
$last = 'Doe';
$age = '32';
$sex = 'male';
NOTE - The array is coming from a serialized jquery string that puts together all the variables and values in a form into one big string.
Is this possible?
You don't need a loop, you want extract:
extract($_POST); // But use caution, see below
Cautions and best practices
As noted in the comments this forces all parameters in the $_POST array into the current symbol space.
In global space
<?php
extract($_GET);
var_dump($_SERVER); // Can be overwritten by the GET param
?>
The code above illustrates the problem as shown in this answer — some pretty dangerous things can be overwritten in the global space.
Inside a function
function myFunc() {
// (Mostly) empty symbol space! (excluding super globals)
extract($_POST);
}
Inside a function, as the first line, no harm done.
Important note: You might think since $_SERVER is a super global, that this exploit could happen inside a function as well. However, in my testing, on PHP Version 5.3.4, it is safe inside a function — neither $_SERVER, $_POST, $_GET, $_SESSION, or presumably other superglobals, could be overwritten.
With options
You can also use extract with extract_type options that do not overwrite.
The best option to use, in my opinion, is simply to prefix all variables from extract:
// $_GET = test=1&name=Joe
extract($_GET, EXTR_PREFIX_ALL, "request_get");
echo $request_get_test; // 1
echo $request_get_name; // Joe
That way you don't have the overwrite problem, but you also know you got everything from the array.
Alternate - looping w/ conditional
If you wanted to do this manually (but still dynamically), or wanted to conditionally extract only a few of the variables, you can use variable variables:
foreach ($_POST as $key => $value) {
if (isset($$key)) continue;
$$key = $value;
}
(The example condition I've used is an overwrite prevention.)
Try not to use extract() when using $_POST. You may overwrite variables you want which will result in unpredictable behaviour. It is a bad habit to get into and while is dynamic may not be the best solution.
You can do something like this:
foreach($_POST as $key => $value)
{
switch($key)
{
case "name":
$name = $value;
break;
case "last":
$last = $value;
break;
}
}
You can actually use the built-in function called extract
Why not use a foreach?
foreach($_POST as $key=>$val){
${$key} = $val;
}
I just want to mention that you can improve foreach technique because we have in HTML the ability to name one of our form fields using square bracket notation, and if we do that, what HTML will do is it will submit a series of values as an array.
<input name="user[name]">
<input name="user[last]">
<input name="user[age]">
<input name="user[sex]">
Than use just one line of code to assign all values from input fields into local array $args.
$args = $_POST['user'];
So what that means is when we go to process the form, we're looking at an array of values instead of a bunch of single values that we have to go retrieve.
So we can just simply go to the post super global and ask for one item: that is user. And what we get back is an associative array. So instead of having to build up that array by going and retrieving all those values one at a time, we're instantly given an array, just because we named our form fields differently.

Categories