Get POST variable using wildcard or regex - php

How to get POST variable using regex like this:
$var = $_POST['foo?'];
or
$var = $_POST['foo\w{1}'];
Edit:
My form has many buttons with separate names: file1, file2, file3. When pressing a button, of course it pass file1 or file2, ... I want to get the value using that name.

The easiest thing I can think of is this:
$allPostKeys = implode(',',array_keys($_POST));
$wildcardVals = array();
if (preg_match_all('/,?(foo[0-9]),?/',$allPostKeys,$matches))
{
$wildCardKeys = $matches[1];
while($key = array_shift($wildCardKeys))
{
$wildcardVals[$key] = $_POST[$key];
}
}
if (!empty($wildcardVals))
{//do stuff with all $_POST vals that you needed
}
Replace [0-9] in the regex with . to match any char, or whatever you need to see matched.
Tested this out with an array that had the following keys bar,zar,foo1,foo2,foo3, and it returned array('foo1' => 'val1','foo2' => 'val2','foo3' => 'val3'), which is what you need, I think.
In response to your edit
The $_POST super-global can be a multi dimensional array, too:
<input type="file" name="file[]" id="file1"/>
<input type="file" name="file[]" id="file2"/>
<input type="file" name="file[]" id="file3"/>
That way, you can easily loop through the files:
foreach($_POST['file'] as $file)
{
//process each file individually: $file is the value
}

run in a loop through the array, and check on the keys
like:
// some POST: array('a' => 1, 'b' => 2, 'cc11' => 6666666)
foreach( $_POST as $k => $v ) {
if ( preg_match('#^[^\d]+$#', $k) ) { // not number key
// you actions ...
}
}

You'd have to loop through the $_POST array:
$regex = "#foo\w{1}#";
$vars = array();
foreach($_POST as $name=>$value) {
if(preg_match($regex, $name)) {
$vars[$name] = $value;
}
}
Hope this helps.

In your case, you could do this:
<?php
$_POST = array(
"foo" => "bar",
"file1" => "something",
"file2" => "somethingelse",
"file3" => "anothervalue",
"whocares" => "aboutthis"
);
$files = array();
foreach ($_POST as $key => $value) {
if (preg_match("/file(\d+)/", $key, $match)) {
$files[$match[1]] = $value;
}
}
print_r($files);
?>
Output (where the key matches file[NUMBER]):
Array (
[1] => something
[2] => somethingelse
[3] => anothervalue
)

Name your form fields as array data structures:
<input name="files[]" ...>
foreach ($_POST['files'] as $file) {
...
}

Related

How can I get keys of a name attribute

I have this name="opt['.$id.']" value="'.$points.'" inside a checkbox input.Does anybody knows how I can get the $id?
UPDATED:
foreach($_POST['opt'] as $id => $value) {
$gift_ids = $value;
$gift_ids2 = implode(", ", $gift_ids);
}
echo $gift_ids2;
}
But I don't get any value on echo..
You need to iterate over the HTML array. Something like this should do it for you:
foreach($_POST['opt'] as $id => $value) {
Demo: https://eval.in/585379
your used array so you need to Iterate the $_POST['opt'] value
$_POST = array('opt' => array('1'=>100 ), 'eksasrgirwsh' => 'other');
foreach($_POST['opt'] as $id => $value)
{
echo $id //key example 1
echo $value //value example 100
}
If your $_POST is like this
$_POST = array('opt' => array('1'=>100 ), 'eksasrgirwsh' => 'other');
and you are giving $_POST['opt'] to foreach then your array for foreach is
$_POST['opt'] = array('1'=>100);
then you can't use implode in foreach because it give you an error. Do it without implode.
foreach($_POST['opt'] as $id => $value) {
$gift_ids = $value;
echo $gift_ids;
}

How to store each array value in a variable with PHP

I have an array that looks something like this:
Array
(
[2] => http://www.marleenvanlook.be/admin.php
[4] => http://www.marleenvanlook.be/checklogin.php
[5] => http://www.marleenvanlook.be/checkupload.php
[6] => http://www.marleenvanlook.be/contact.php
)
What I want to do is store each value from this array to a variable (using PHP). So for example:
$something1 = "http://www.marleenvanlook.be/admin.php";
$something2 = "http://www.marleenvanlook.be/checklogin.php";
...
You can use extract():
$data = array(
'something1',
'something2',
'something3',
);
extract($data, EXTR_PREFIX_ALL, 'var');
echo $var0; //Output something1
More info on http://br2.php.net/manual/en/function.extract.php
Well.. you could do something like this?
$myArray = array("http://www.marleenvanlook.be/admin.php","http://www.marleenvanlook.be/checklogin.php","etc");
$i = 0;
foreach($myArray as $value){
${'something'.$i} = $value;
$i++;
}
echo $something0; //http://www.marleenvanlook.be/admin.php
This would dynamically create variables with names like $something0, $something1, etc holding a value of the array assigned in the foreach.
If you want the keys to be involved you can also do this:
$myArray = array(1 => "http://www.marleenvanlook.be/admin.php","http://www.marleenvanlook.be/checklogin.php","etc");
foreach($myArray as $key => $value){
${'something'.$key} = $value;
}
echo $something1; //http://www.marleenvanlook.be/admin.php
PHP has something called variable variables which lets you name a variable with the value of another variable.
$something = array(
'http://www.marleenvanlook.be/admin.php',
'http://www.marleenvanlook.be/checklogin.php',
'http://www.marleenvanlook.be/checkupload.php',
'http://www.marleenvanlook.be/contact.php',
);
foreach($something as $key => $value) {
$key = 'something' . $key;
$$key = $value;
// OR (condensed version)
// ${"something{$key}"} = $value;
}
echo $something2;
// http://www.marleenvanlook.be/checkupload.php
But the question is why would you want to do this? Arrays are meant to be accessed by keys, so you can just do:
echo $something[2];
// http://www.marleenvanlook.be/checkupload.php
What I would do is:
$something1 = $the_array[2];
$something2 = $the_array[4];

Get keys from multidimensional array according to other keys

I have a multidimensional array like this which I converted from JSON:
Array (
[1] => Array (
[name] => Test
[id] => [1]
)
[2] => Array (
[name] => Hello
[id] => [2]
)
)
How can I return the value of id if name is equal to the one the user provided? (e.g if the user typed "Test", I want it to return "1")
Edit: Here's the code that works if anyone wants it:
$array = json_decode(file_get_contents("json.json"), true);
foreach($array as $item) {
if($item["name"] == "Test")
echo $item["id"];
}
The classical solution is to simply iterate over the array with foreach and check the name of each row. When it matches your search term you have found the id you are looking for, so break to stop searching and do something with that value.
If you are using PHP 5.5, a convenient solution that works well with less-than-huge data sets would be to use array_column:
$indexed = array_column($data, 'id', 'name');
echo $indexed['Test']; // 1
You can use this function
function searchObject($value,$index,$array) {
foreach ($array as $key => $val) {
if ($val[$index] === $value)
return $val;
}
return null;
}
$MyObject= searchObject("Hello","name",$MyArray);
$id = $MyObject["id"];
You can do it manually like, in some function:
function find($items, $something){
foreach($items as $item)
{
if ($item["name"] === $something)
return $item["id"];
}
return false;
}
here is the solution
$count = count($array);
$name = $_POST['name']; //the name which user provided
for($i=1;$i<=$count;$i++)
{
if($array[$i]['name']==$name)
{
echo $i;
break;
}
}
enjoy
Try this:
$name = "Test";
foreach($your_array as $arr){
if($arr['name'] == $name){
echo $arr['id'];
}
}

php array keys problem

I have the following code:
$rt1 = array
(
'some_value1' => 'xyz1',
'some_value2' => 'xyz2',
'value_1#30'=>array('0'=>1),
'value_2#30'=>array('0'=>2),
'value_3#30'=>array('0'=>3),
'value_1#31'=>array('0'=>4),
'value_2#31'=>array('0'=>5),
'value_3#31'=>array('0'=>6),
'some_value3' => 'xyz3',
'some_value4' => 'xyz4',
);
$array_30 = array
(
'0'=>1,
1=>'2',
2=>'3'
);
$array_31 = array
(
'0'=>4,
'1'=>'5',
'2'=>'6'
);
I need to make it an array and insert the array_30 and array_31 into a DB.
foreach($rt1 as $value){
$rt2[] = $value['0'];
}
The question was updated, so here is an updated answer. Quick check, you should really try and update this to whatever more generic purpose you have, but as a proof of concept, a runnable example:
<?php
$rt1 = array
(
'some_value1' => 'xyz1',
'some_value2' => 'xyz2',
'value_1#30'=>array('0'=>1),
'value_2#30'=>array('0'=>2),
'value_3#30'=>array('0'=>3),
'value_1#31'=>array('0'=>4),
'value_2#31'=>array('0'=>5),
'value_3#31'=>array('0'=>6),
'some_value3' => 'xyz3',
'some_value4' => 'xyz4',
);
$finalArrays = array();
foreach($rt1 as $key=>$value){
if(is_array($value)){
$array_name = "array_".substr($key,-2);
${$array_name}[] = $value['0'];
}
}
var_dump($array_30);
var_dump($array_31);
?>
will output the two arrays with the numbers 1,2,3 and 4,5,6 respectivily
i assume you want to join the values of each of the second-level arrays, in which case:
$result = array();
foreach ($rt1 as $arr) {
foreach ($arr as $item) {
$result[] = $item;
}
}
Inspired by Nanne (which reminded me of dynamically naming variables), this solution will work with every identifier after the \#, regardless of its length:
foreach ( $rt1 as $key => $value )
{
if ( false == strpos($key, '#') ) // skip keys without #
{
continue;
}
// the part after the # is our identity
list(,$identity) = explode('#', $key);
${'array_'.$identity}[] = $rt1[$key]['0'];
}
Presuming that this is your actual code, probably you will need to copy the array somewhere using foreach and afterwards create the new array as you wish:
foreach($arr as $key => $value) {
$arr[$key] = 1;
}

PHP: Retrieving value of checkboxes when name doesn't have array

A form I don't have any control over is POSTing data to my PHP script. The form contains checkboxes along these lines:
<input type="checkbox" value="val1" name="option"/>
<input type="checkbox" value="val2" name="option"/>
If I were to write the code for the form, I'd write name="option[]" instead of name="option". But this is not a change I can do. Now, if both checkboxes are checked, $_POST["option"] returns just one of the values. How can I, in PHP retrieve all the values selected?
You can read the raw post data. For example:
<fieldset>
<legend>Data</legend>
<?php
$data = file_get_contents("php://input");
echo $data."<br />";
?>
</fieldset>
<fieldset>
<legend>Form</legend>
<form method="post" action="formtest.php">
<input type="checkbox" value="val1" name="option"/><br />
<input type="checkbox" value="val2" name="option"/><br />
<input type="submit" />
</form>
</fieldset>
Check both boxes and the output will be:
option=val1&option=val2
Here's a live demo. All you have to do then is to parse the string yourself, into a suitable format. Here's an example of a function that does something like that:
function parse($data)
{
$pairs = explode("&", $data);
// process all key/value pairs and count which keys
// appear multiple times
$keys = array();
foreach ($pairs as $pair) {
list($k,$v) = explode("=", $pair);
if (array_key_exists($k, $keys)) {
$keys[$k]++;
} else {
$keys[$k] = 1;
}
}
$output = array();
foreach ($pairs as $pair) {
list($k,$v) = explode("=", $pair);
// if there are more than a single value for this
// key we initialize a subarray and add all the values
if ($keys[$k] > 1) {
if (!array_key_exists($k, $output)) {
$output[$k] = array($v);
} else {
$output[$k][] = $v;
}
}
// otherwise we just add them directly to the array
else {
$output[$k] = $v;
}
}
return $output;
}
$data = "foo=bar&option=val1&option=val2";
print_r(parse($data));
Outputs:
Array
(
[foo] => bar
[option] => Array
(
[0] => val1
[1] => val2
)
)
There might be a few cases where this function doesn't work as expected though, so be careful.

Categories