If i send four POST variables, but the second one — I dont know that th开发者_StackOverflow社区e 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.
精彩评论