transferring values within elements of $_POST to pre-existing array - php

I have the following associative array stored in a php file also containing a database connect statement.
$fields = array(
"A" => "A",
"B" => "B",
"C" => "C",
...
);
Here I am calling it
include('dbconnection.php');
What I intended from this code is that the $field values within $_POST[$field] would be transferred over to values stored within $fields.
if (isset($_POST['submit'])){
//iterating through fields array
foreach($fields as $column => $field){
//cleaning and storing user input in fields array
$field = mysqli_real_escape_string($cxn , htmlspecialchars($_POST[$field]));
}
These new $fields array values would then be transferred over to $emptyArray, where elements of the array containing 0, NULL, FALSE, or "" values would be filtered out.
$emptyArray = array();
$emptyArray = array_merge ($emptyArray, array_values($fields));
$emptyArray = array_filter($emptyArray);
Finally, after checking if there were any elements stored in $emptyArray, an error message would be issued, along with a call to run function renderform.
if (empty($emptyArray)){
$error = 'You have reached this message because you did not specify a field to update';
renderForm($id, $fields, $error);
}
}
function renderform contains the argument $fields, the first array in this chain, which is why I chose to use $emptyArray instead of $fields in order to conserve its structure.
However, if I run print_r of $fields and $emptyArray immediately before renderform, I receive arrays identical to keys and values stored in $fields prior to their manipulation
Array ( [A] => A [B] => B [C] => C [...] => ...)
Can I use $_POST[$field] in the way that I'm intending ($field values within $_POST[$field] being transferred over to values stored within $fields)? If so, is this good practice?
Thanks for reading,
I'm happy to answer any questions.

You could do this in a single loop:
$fields = array(
"A" => "A",
"B" => "B",
"C" => "C",
);
$post=[];
foreach($fields as $key => $val){
if(!isset($_POST[$key]) || !$_POST[$key]){
die("data for $key is incorrect or missing");
}
$post[$key] = mysqli_real_escape_string($cxn , htmlspecialchars($_POST[$key]));
}
//all is fine, use $post array for whatever you need it for

Related

How to check if array contains certain value for specific key when the parent array is not associative?

I have the following array that contains associative arrays:
array(
[0] => array ("name" => "foo", //more key-value pairs)
[1] => array ("name" => "bar", //more key-value pairs)
[2] => array ("name" => "baz", //more key-value pairs)
)
How can I check if a name exists while iterating over another array of names:
foreach ($list_of_names as $name) {
// does the current name exist in the other array?
}
Is there a way to do it without nesting foreach loop inside the foreach loop?
Your question is a bit vague. I understand that you ask whether it is possible to check if any of the inner arrays contains a given key without using two nested foreach loops.
If so then take a look at this example:
<?php
$data = [
["name-foo" => "foo"],
["name-bar" => "bar"],
["name-baz" => "baz"],
];
$needle = "name-bar";
array_walk($data, function($entry) use ($needle) {
var_dump(
array_key_exists($needle, $entry)
? "$needle exists"
: "$needle does NOT exist"
);
});
The output obviously is:
string(23) "name-bar does NOT exist"
string(15) "name-bar exists"
string(23) "name-bar does NOT exist"
In the end there is no way around having to iterate over all entries in the nested arrays. But you don't have to do that explicitly in the calling scope, you can use the many convenience functions php offers, here array_key_exists(...) for example.
If you just need to know if the name exists, you could extract the name values (using array_column()) and (in this case) using aray_flip() to make it an associative array. This allows you to use isset() inside the loop and not have to do any nested loops.
$data = [
['name' => 'foo'], //more key-value pairs)
['name' => 'bar'], //more key-value pairs)
['name' => 'baz'], //more key-value pairs)
];
$list_of_names = [
'foo',
'bart'
];
$dataNames = array_flip(array_column($data, 'name'));
foreach ($list_of_names as $name) {
if (isset($dataNames[$name])) {
echo "$name exists" . PHP_EOL;
} else {
echo "$name does not exist" . PHP_EOL;
}
}
will show
foo exists
bart does not exist

PHP getting dynamic $_POST content

So I'm trying to get dynamic data from the $_POST array. The $_POST array looks like this after the form submit:
Array
(
[teams1member3] => on
[teams1member4] => on
[teams1member7] => on
[teams1member8] => on
[teams2member1] => on
)
Now I'm not entirely sure how I can access these, the teams can be any number and the same goes for a member. Is there a way to "read" the [teams1member3]?
I tried looping through the $_POST variable with a foreach loop (foreach($_POST as $post)), but this only gets the value (on). If I'm able to get the teams1member3, teams1member4, etc. I should be able to continue.
Anyone that can help me out? Much appreciated!
You should use the $key => $value syntax:
foreach($_POST as $key => $post){
// $key is what you need
}
But you should rather serialise your $_POST data better, consider using the following JSON notation:
{
"teams" : [
{
"id": 1,
"members": [3, 4, 7, 8]
},
{
"id": 2,
"members": [1]
}
]
}
foreach ($_POST as $key => $value) {
// ...
}
$key will contain array keys (what you need), $value - string "on".
if you just use foreach($_POST as $value) , you will only get the values - in your case on and off
However, if you want the actual field name, you have to specify key and value in your foreach:
foreach($_POST a $key => $value) {
//$key contains teammember
//$value contains on
}

Flip key/value pairs from an existing array into an associate array which allows for keys with multiple values in PHP

I need to basically flip an existing associate array into another associate array. It needs to contain the keys from the previous array as values and the values of the previous array as keys. Also, it needs to be able to contain multiple values for a single key.
Code:
class Owner {
public static function groupOwners($array)
{
//insert code
}
}
$array = array(
"Input.txt" => "Bob",
"Code.py" => "Steve",
"Output.txt" => "Bob"
);
var_dump(Owner::groupOwners($array));
The output generated is to be:
["Bob"] => ["Input.txt, Output.txt"], ["Steve"] => ["Code.py"]
You didn't show an attempt but I'm bored:
foreach($array as $key => $val) {
$result[$val][] = $key;
}

php extract sub array with specific key

if i have the following array:
array(
'var1' => 123,
'var2' => 234,
'var3' => 345
);
I would like to extract specific parts of this to build a new array i.e. var1 and var3.
The result i would be looking for is:
array(
'var1' => 123,
'var3' => 345
);
The example posted is very stripped down, in reality the array has a much larger number of keys and I am looking to extract a larger number of key and also some keys may or may not be present.
Is there a built in php function to do this?
Edit:
The keys to be extracted will be hardcoded as an array in the class i..e $this->keysToExtract
$result = array_intersect_key($yourarray,array_flip(array('var1','var3')));
So, with your edit:
$result = array_intersect_key($yourarray,array_flip($this->keysToExtract));
You don't need a built in function to do this, try this :
$this->keysToExtract = array('var1', 'var3'); // The keys you wish to transfer to the new array
// For each record in your initial array
foreach ($firstArray as $key => $value)
{
// If the key (ex : 'var1') is part of the desired keys
if (in_array($key, $this->keysToExtract)
{
$finalArray[$key] = $value; // Add to the new array
}
}
var_dump($finalArray);
Note that this is most likely the most efficient way to do this.

Add 2 values to 1 key in a PHP array

I have a result set of data that I want to write to an array in php. Here is my sample data:
**Name** **Abbrev**
Mike M
Tom T
Jim J
Using that data, I want to create an array in php that is of the following:
1|Mike|M
2|Tom|T
3|Jim|j
I tried array_push($values, 'name', 'abbreviation') [pseudo code], which gave me the following:
1|Mike
2|M
3|Tom
4|T
5|Jim
6|J
I need to do a look up against this array to get the same key value, if I look up "Mike" or "M".
What is the best way to write my result set into an array as set above where name and abbreviation share the same key?
PHP's not my top language, but try these:
array_push($values, array("Mike", "M"))
array_push($values, array("Tom", "T"))
array_push($values, array("Jim", "J"))
$name1 = $values[1][0]
$abbrev1 = $values[1][1]
or:
array_push($values, array("name" => "Mike", "abbrev" => "M"))
array_push($values, array("name" => "Tom", "abbrev" => "T"))
array_push($values, array("name" => "Jim", "abbrev" => "J"))
$name1 = $values[1]["name"]
$abbrev1 = $values[1]["abbrev"]
The trick is to use a nested array to pair the names and abbreviations in each entry.
$person = array('name' => 'Mike', 'initial' => 'M');
array_push($people, $person);
That said, I'm not sure why you're storing the data separately. The initial can be fetched directly from the name via substr($name, 0, 1).
You will need to create a two dimensional array to store more than one value.
Each row in your result set is already an array, so it will need to be added to your variable as an array.
array_push($values, array('name', 'abbreviation'));
maybe you create a simple class for that as the abbreviation is redundant information in your case
class Person
{
public $name;
pulbic function __construct($name)
{
$this->name = (string)$name;
}
public function getAbbrev()
{
return substr($this->name, 0, 1);
}
public function __get($prop)
{
if ($prop == 'abbrev') {
return $this->getAbbrev();
}
}
}
$persons = array(
new Person('Mike'),
new Person('Tom'),
new Person('Jim')
);
foreach ($persons as $person) {
echo "$person->name ($person->abbrev.)<br/>";
}
You could use two separate arrays, maybe like:
$values_names = array();
$values_initials = array();
array_push($values_names, 'Mike');
array_push($values_initials, 'M');
array_push($values_names, 'Tom');
array_push($values_initials, 'T');
array_push($values_names, 'Jim');
array_push($values_initials, 'J');
So you use two arrays, one for each of the second and third columns using the values in the first one as keys for both arrays.
php arrays work like hash lookup tables, so in order to achieve the desired result, you can initialize 2 keys, one with the actual value and the other one with a reference pointing to the first. For instance you could do:
$a = array('m' => 'value');
$a['mike'] = &$a['m']; //notice the end to pass by reference
if you try:
$a = array('m' => 'value');
$a['mike'] = &$a['m'];
print_r($a);
$a['m'] = 'new_value';
print_r($a);
$a['mike'] = 'new_value_2';
print_r($a);
the output will be:
Array
(
[m] => value
[mike] => value
)
Array
(
[m] => new_value
[mike] => new_value
)
Array
(
[m] => new_value_2
[mike] => new_value_2
)
have to set the same value to both Mike and M for keys.

Categories