PHP $_POST array - php

I'm building a webhook that will receive data from an external service.
In order to retrieve data, I'm using the following array:
$data = [
$_POST['aaa'],
$_POST['bbb'],
$_POST['ccc'],
$_POST['ddd'],
$_POST['eee']
];
Is it possible to build the same array without repeating $_POST? I mean something like:
$data = $_POST [
['aaa'],
['bbb'],
['ccc'],
['ddd'],
['eee']
];
Obviously, that code is wrong.
Thanks.

There's no shortcut like that. You could use array_map():
$data = array_map(function($key) {
return $_POST[$key];
}, ['aaa', 'bbb', 'ccc', ...]);

$data = $_POST
This will build your new $data array the same way as your GLOBAL $_POST array including the POST Key names and their assigned values.
Also checkout extract($_POST), as this will extract each key to its same name variable, which may be easier to then reference in your web-hook or any functions or procedural code you uses from then on. This essentially does this:
$aaa = $POST['aaa']
$bbb = $POST['bbb']
$ccc = $POST['ccc']
etc etc
https://www.php.net/manual/en/function.extract.php

The simplest way for me would be:
For getting all the values in the $_POST array
foreach($_POST as $value){
$data[] = $value;
}
For getting all the values and want to keep the key
foreach($_POST as $key=>$value){
$data[$key] = $value;
}
For getting a specific array of values from the array
foreach(['aaa','bbb','ccc','ddd','eee'] as $column){
$data[] = $_POST[$column];
}
Just a good idea to always escape variables ;)
$con = mysqli_connect('hostcleveranswer.com','USERyouearn','PWDanupv0Te','dropthemicDB')
foreach($_POST as $key => $value) {
$data[] = mysqli_escape_string($con,$value);
}
//i feel that was a good simple answer using tools without having to a learn a new function syntax

Related

PHP - Associative array

Consider the structure for an associative array and a function which are composed by structure below:
$myCars = array("name" => "categories", "data" => array());
function getCategoriesData()
{
// data is gathered here
return $categoriesData
}
The “data” array should be populated with the return of the “getCategoriesData” function.
Considering that, how can I perform that action using a foreach loop?
Assuming that getCategoriesData() returns an Array, if you specifically need to use a foreach loop, we can write the code like this
$returnedArray = getCategoriesData();
foreach($returnedArray as $key => $value)
{
$myCars["data"][$key] = $value;
}
An even simpler approach would be this.
$mycars["data"] = getCategoriesData();

How to get all $_POST[] data from a randomly generated <form>

I generate several forms with different <input> name attributes and I can not exactly define all input-names for fetching them after posting.
How can I receive ALL $_POST data from the form (without having a name-attribute) and put them in an array like that:
'name_attribute' => 'value'
A basic loop will do this:
$post = array();
foreach ($_POST as $key => $value) {
$post[$key] = $value;
}
I don't know how this benefits you though as all you have done is remake your $_POST superglobal.
With any POSTs, php puts it into the array $_POST. You can treat this like any array and just loop through each key/value of the POST.
$your_array = array();
foreach ($_POST as $key => $val){
$your_array[$key] = $val;
}
to make this more secure, I would suggested escaping the $val by using other php functions such as mysql_real_escape_string(), trim(), htmlspecialchars().
Try this code
$post = $_POST;
foreach($post as $name => $value)
{
echo $name." = ".$value;
}
$_POST is an associative array in the format
'field_name' => 'field_value'

ow to handle possible duplicate array keys

I am trying to figure out how I can handle possible duplicate array keys.
I have this form with a select dropdown which can select multiple options (more than 1). And I am using jQuery.serialize() to serialize the form on submit.
The serialized string for a multi-select element would look like so:
select=1&select=2&select=3 // assumming I selected first 3 options.
Now in the PHP side, I have the following code to handle the "saving" part into a database.
$form_data = $_POST['form_items'];
$form_data = str_replace('&','####',$form_data);
$form_data = urldecode($form_data);
$arr = array();
foreach (explode('####', $form_data) as $part) {
list($key, $value) = explode('=', $part, 2);
$arr[$key] = $value;
}
Ok this all works for the rest of the form elements but when it comes to the select element, it only picks the last selected key/value pair. So my array now looks like this:
Array ( [select_element] => 3)
What I need, is for it to look like:
Array ( [select_element] => '1,2,3')
So I guess what I am asking is based on my code, how can I check if a key already exists and if it does, append to the $value.
If you can modify the client-side code, I would rather change the name of the select to select[], that way it will be parsed as an array in your server script.
You can't have multiple keys with the same name... They're unique keys. What it's doing is setting select = 1, then select = 2, then select = 3 and you end up with your final value of 3.
If you want to allow multiple choices in your select menu, you should change the name of the element so that it submits that data as an array, rather than multiple strings:
<select name="select[]" multiple="multiple">
which should result in something like this instead:
select[]=1&select[]=2&select[]=3
and when PHP requests that data, it will already be an array:
$data = $_POST['select'];
echo print_r($data); // Array(1, 2, 3)
PHP has its own way of encoding arrays into application/x-www-form-urlencoded strings.
PHP's deserialization of x-www-form-urlencoded is implemented by parse_str(). You can think of PHP as running these lines at the beginning of every request to populate $_GET and $_POST:
parse_str($_SERVER['QUERY_STRING'], $_GET);
parse_str(file_get_contents('php://input'), $_POST);
parse_str() creates arrays from the query string using a square-bracket syntax similar to its array syntax:
select[]=1&select[]=2&select[]=3&select[key]=value
This will be deserialized to:
array('1', '2', '3', 'key'=>'value');
Absent those square brackets, PHP will use the last value for a given key. See this question in the PHP and HTML FAQ.
If you can't control the POSTed interface (e.g., you're not able to add square-brackets to the form), you can parse the POST input yourself from php://input and either rewrite or ignore the $_POST variable.
(Note, however, that there is no workaround for multipart/form-data input, because php://input is not available in those cases. The select=1 and select=2 will be completely and irretrievably lost.)
Ok, I was able to resolve this issue by using the following code:
if (array_key_exists($key, $arr)) {
$arr[$key] = $arr[$key].','.$value;
} else {
$arr[$key] = $value;
}
So now the loop looks like this:
foreach (explode('####', $form_data) as $part) {
list($key, $value) = explode('=', $part, 2);
if (array_key_exists($key, $arr)) {
$arr[$key] = $arr[$key].','.$value;
} else {
$arr[$key] = $value;
}
}
This will essentially string up the value together separated by a comma which can then be exploded out into an array later.
You should change your client-side code to send the augmented value: array.join(","); and use that in your PHP side. Because when your data reaches your script, the other values have already been lost.
This should give you the solution you require
$form_data = str_replace('&','####',$form_data);
$form_data = urldecode($form_data);
$arr = array();
foreach (explode('####', $form_data) as $part) {
list($key, $value) = explode('=', $part, 2);
if (isset($arr[ $key ])) {
$arr[$key] = ','.$value;
} else {
$arr[$key] = $value;
}
}

Better way to unset multiple array elements

The deal here is that I have an array with 17 elements. I want to get the elements I need for a certain time and remove them permanently from the array.
Here's the code:
$name = $post['name'];
$email = $post['email'];
$address = $post['address'];
$telephone = $post['telephone'];
$country = $post['country'];
unset($post['name']);
unset($post['email']);
unset($post['address']);
unset($post['telephone']);
unset($post['country']);
Yes the code is ugly, no need to bash. How do I make this look better?
Use array_diff_key to remove
$remove = ['telephone', 'country'];
$remaining = array_diff_key($post, array_flip($remove));
You could use array_intersect_key if you wanted to supply an array of keys to keep.
It looks like the function extract() would be a better tool for what you're trying to do (assuming it's extract all key/values from an array and assign them to variables with the same names as the keys in the local scope). After you've extracted the contents, you could then unset the entire $post, assuming it didn't contain anything else you wanted.
However, to actually answer your question, you could create an array of the keys you want to remove and loop through, explicitly unsetting them...
$removeKeys = array('name', 'email');
foreach($removeKeys as $key) {
unset($arr[$key]);
}
...or you could point the variable to a new array that has the keys removed...
$arr = array_diff_key($arr, array_flip($removeKeys));
...or pass all of the array members to unset()...
unset($arr['name'], $arr['email']);
There is another way which is better then the above examples.
Source: http://php.net/manual/en/function.unset.php
Instead of looping thorough the entire array and unsetting all its keys, you can just unset it once like so:
Example Array:
$array = array("key1", "key2", "key3");
For the entire array:
unset($array);
For unique keys:
unset($array["key1"]);
For multiple keys in one array:
unset($array["key1"], $array["key2"], $array["key3"] ....) and so on.
I hope this helps you in your development.
I understand this question is old, but I think an optimal way might be to do this:
$vars = array('name', 'email', 'address', 'phone'); /* needed variables */
foreach ($vars as $var) {
${$var} = $_POST[$var]; /* create variable on-the-fly */
unset($_POST[$var]); /* unset variable after use */
}
Now, you can use $name, $email, ... from anywhere ;)
NB: extract() is not safe, so it's completely out of question!
<?php
$name = $post['name'];
$email = $post['email'];
$address = $post['address'];
$telephone = $post['telephone'];
$country = $post['country'];
$myArray = array_except($post, ['name', 'email','address','telephone','country']);
print_r($myArray);
function array_except($array, $keys){
foreach($keys as $key){
unset($array[$key]);
}
return $array;
}
?>
In php unset function can take multiple arguments
$test = ['test1' => 1, 'test2' => 4, 'test34' => 34];
unset($test['test1'], $test['test34']);
Here is this description from documentation
unset(mixed $var, mixed ...$vars): void

Make 1d Array from 1st member of each value in 2d Array | PHP

How can you do this? My code seen here doesn't work
for($i=0;i<count($cond);$i++){
$cond[$i] = $cond[$i][0];
}
It can be as simple as this:
$array = array_map('reset', $array);
There could be problems if the source array isn't numerically index. Try this instead:
$destinationArray = array();
for ($sourceArray as $key=>$value) {
$destinationArray[] = $value[0]; //you may want to use a different index than '0'
}
// Make sure you have your first array initialised here!
$array2 = array();
foreach ($array AS $item)
{
$array2[] = $item[0];
}
Assuming you want to have the same variable name afterwards, you can re-assign the new array back to the old one.
$array = $array2;
unset($array2); // Not needed, but helps with keeping memory down
Also, you might be able to, dependant on what is in the array, do something like.
$array = array_merge(array_values($array));
As previously stated, your code will not work properly in various situation.
Try to initialize your array with this values:
$cond = array(5=>array('4','3'),9=>array('3','4'));
A solution, to me better readable also is the following code:
//explain what to do to every single line of the 2d array
function reduceRowToFirstItem($x) { return $x[0]; }
// apply the trasnformation to the array
$a=array_map('reduceRowTofirstItem',$cond);
You can read the reference for array map for a thorough explanation.
You can opt also for a slight variation using array_walk (it operate on the array "in place"). Note that the function doesn't return a value and that his parameter is passed by reference.
function reduceToFirstItem(&$x) { $x=$x[0]; }
array_walk($cond, 'reduceToFirstItem');
That should work. Why does it not work? what error message do you get?
This is the code I would use:
$inArr;//This is the 2D array
$outArr = array();
for($i=0;$i<count($inArr);$i++){
$outArr[$i] = $inArr[$i][0];
}

Categories