Easier to put $_POST With Array - php

I did try many times to make values easier to put. It's my meaning to put values with array, because I don't need to type more values then, he can put it automatically.. For example, I write:
<?php
$Value1 = array (
'Somevalue1' => 'SomeValue2',
'SomeValue1' => 'SomeValue2',
'SomeValue1' => 'SomeValue2',
);
// This is method what i want to put in, but i dont think that its right
$Value1[0] = strip_tags($_POST['.Value1[0].']);
// Its the meaning that he put so out:
$SomeValue1 = strip_tags($_POST['SomeValue2']);
$SomeValue1 = strip_tags($_POST['SomeValue2']);
$SomeValue1 = strip_tags($_POST['SomeValue2']);
?>
I don't have to much experience with array, I am just learning...

I guess it is this what you want to do:
// create an array with key = field-name in form
$val = array(
'name' => null,
'lastname' => null,
'date_of_birth' => null,
'favorite_color' => null);
if (isset($_POST['submit'])) { // form has been sent
// retrieve values from $_POST and store it in $val
foreach ($val as $key => $value)
$val[$key] = $_POST[$key];
// show the result
echo "<pre>";
var_dump($val);
echo "</pre>";
} // if isset
see live demo: http://codepad.viper-7.com/j03DtO

Related

PHP - Put variables with a prefix into array

Is there any way of putting variables into an array? I'm not really sure how else to explain it.
I'm developing a website that works with a game server.
The game exports a file which contains variables such as:
$RL_PlayerScore_CurrentTrail_14911 = "lasergold";
$RL_PlayerScore_HasTrail_14911_LaserGold = 1;
$RL_PlayerScore_Money_14911 = 2148;
I'd like to convert these into an array like
$data = array(
'CurrentTrail_14911' => 'lasergold'
'HasTrail_14911_LaserGold' => '1'
'Money_14911' => '2184'
);
Is there any way I could do this?
Thanks in advance
Include file in scope and then get array of defined vars, excluding globals you don't need.
include('name-of-your-file.php');
$data = get_defined_vars();
$data = array_diff_key($data, array(
'GLOBALS' => 1,
'_FILES' => 1,
'_COOKIE' => 1,
'_POST' => 1,
'_GET' => 1,
'_SERVER' => 1,
'_ENV' => 1,
'ignore' => 1 )
);
You can return an array with all your declared variables, and loop through them cutting off the desired piece of text. You could do something like this:
<?php
//echo your generated file here;
$generatedVars = get_defined_vars();
$convertedArray = array();
foreach($generatedVars as $key=>$var)
{
$key = str_replace("RL_PlayerScore_","",$key);
$convertedArray[$key] = $var;
}
If all game variables are going to begin with 'RL_PlayerScore_', you could use something like that :
$vars = [];
foreach($GLOBALS as $var => $value) {
if(strpos($var, 'RL_PlayerScore_') === 0) {
$vars[$var] = $value;
}
}
$vars will be filled by all your variables.
See #Dagon comment also.

Merge array with varying key value pairs

So I have various arrays which do not always have the same key/value pairs in them. What I want to do is to be able to merge the arrays, but to add in empty key/value pairs if they don't already exist in that array, but do in others. It's hard to explain but this might explain it better:
$arrayOne = array('name' => 'rory', 'car' => 'opel');
$arrayTwo = array('name' => 'john', 'dog' => 'albert');
I need to somehow turn this into:
$finalArray = array(
array('name' => 'rory', 'car' => 'opel', 'dog' => ''),
array('name' => 'john', 'car' => '', 'dog' => 'albert')
);
I have been looking through PHP's documentation but can't find anything that will do this for me. Can anyone point me in the right direction? I don't even know an appropriate search term for what I want to achieve here, "array merge" isn't specific enough.
<?php
$arrayOne = array('name' => 'rory', 'car' => 'opel');
$arrayTwo = array('name' => 'john', 'dog' => 'albert');
$diff1=array_diff(array_flip($arrayOne), array_flip($arrayTwo));
$diff2=array_diff(array_flip($arrayTwo), array_flip($arrayOne));
//array_flip flips the key of array with value
//array_diff would return the values in the first array that are not present in any of the other arrays inside
foreach ($diff2 as $s) {
$arrayOne[$s]="";
}
foreach ($diff1 as $s) {
$arrayTwo[$s]="";
};
//set key that didn't exist in that array as ""
$finalArray[]=$arrayOne;
$finalArray[]=$arrayTwo;
//add the arrays to the final array
print_r($finalArray);
Here's what I would do:
Merge your separate arrays into one (into a temporary var) using array_merge
Get the unique keys of this new array using array_keys
For each separate array, loop through the new keys array and add an empty value for each key that is not in the array. Then push the separate array into a final array.
<?php
$arrayOne = array('name' => 'rory', 'car' => 'opel');
$arrayTwo = array('name' => 'john', 'dog' => 'albert');
$new = array_merge($arrayOne,$arrayTwo);
$new = array_keys($new);
$newarray = array();
foreach($new as $value){
$newarray[0][$value] = isset($arrayOne[$value]) ? $arrayOne[$value] : '' ;
$newarray[1][$value] = isset($arrayTwo[$value]) ? $arrayTwo[$value] : '' ;
}
echo "<pre>";print_r($newarray);
You can also use this short answer
$arrayOne = array('name' => 'rory', 'car' => 'opel');
$arrayTwo = array('name' => 'john', 'dog' => 'albert');
$defaults = array('name' => '','car' => '','dog' => '');
$arrayOne += $defaults;
$arrayTwo += $defaults;
$newarray = array($arrayOne,$arrayTwo);
echo "<pre>";print_r($newarray);
Basing on what Justin Powell outlined, I managed to come up with this code before the other two code examples were posted (thank you mamta & user6439245).
I also needed to take the keys containing numbers and sort them appropriately, otherwise my keys would've been indexed like employer_1, education_1, employer_2, education_2.
// get the initial form entries data
$entries = array(
array('name' => 'john', 'car' => 'fiat', 'employer_1' => 'tangerine', 'education_1' => 'hideaways', 'education_2' => 'extras'),
array('name' => 'rory', 'car' => 'opel', 'employer_1' => 'sagittarius', 'employer_2' => 'tangerine', 'employer_3' => 'thehideout', 'education_1' => 'knatchbull')
);
// create an empty array to populate with all field keys
$mergedKeys = array();
// push all field keys into the array
foreach($entries as $entry){
foreach($entry as $key => $value){
array_push($mergedKeys, $key);
}
}
// remove duplicate keys from the array
$uniqueMergedKeys = array_unique($mergedKeys);
// create a new array to populate with the field keys we need to sort - the ones with numbers in
$keysToSort = array();
// push the number-containing keys into the array
$i=0;
foreach($uniqueMergedKeys as $uniqueKey){
if(1 === preg_match('~[0-9]~', $uniqueKey)){
array_push($keysToSort, $uniqueKey);
}
$i++;
}
// remove the number containing keys from the unique keys array
$uniqueMergedKeys = array_diff($uniqueMergedKeys, $keysToSort);
// sort the keys that need sorting
sort($keysToSort);
// put the newly sorted keys back onto the original keys array
foreach($keysToSort as $key){
array_push($uniqueMergedKeys, $key);
}
$final = array();
$i = 0;
foreach($entries as $entry){
foreach($uniqueMergedKeys as $key){
//if($entries[$i][$key]){
if (array_key_exists($key, $entries[$i])) {
$final[$i][$key] = $entries[$i][$key];
} else {
$final[$i][$key] = '';
}
}
$i++;
}
echo '<pre>'; print_r($final); echo '</pre>';

Obtain specific piece of PHP array?

I am trying to get a specific value out of a deeply nested PHP array. I have gotten as far as reaching reaching the array that I need and storing it in a variable. The array looks like this:
Array (
[0] => Array (
[social_channel] => twitter
[link] => testing#twitter.com
)
[1] => Array (
[social_channel] => mail
[link] => hcrosby#testing.edu
)
)
Often times this array will contain numerous values such as facebook links, twitter, instagram and they will always be in different orders based on how the user inputs them. How do I only pull out the email address in this array. I know this is basic but PHP is far from my strong point.
Assuming you've got the following:
$my_array = [
['social_channel' => 'twitter', 'link' => 'testing#twitter.com'],
['social_channel' => 'mail', 'link' => 'hcrosby#testing.edu'],
];
You'd could loop over each item of the array using a foreach and then use the link array key to get the email address. For example:
foreach ($my_array as $item) {
echo $item['link']; // Or save the item to another array etc.
}
You can use array_map function
$my_array = [
['social_channel' => 'twitter', 'link' => 'testing#twitter.com'],
['social_channel' => 'mail', 'link' => 'hcrosby#testing.edu'],
];
function getMailArray($array) {
return $array['link'];
}
$result = array_map("getMailArray",$my_array);
Try this:
$arr1 = array(array('social_channel' => 'twitter', 'link' => 'testing#twitter.com'),
array('social_channel' => 'mail', 'link' => 'hcrosby#testing.edu'));
$emailArr = array();
foreach ($arr1 AS $arr) {
$emailArr[] = $arr['link'];
}
print_r($emailArr);
$assoc = [];
foreach($array as $sub){
$assoc[$sub["social_channel"]] = $assoc["link"];
}
The above changes social_channel into a key so that you can search directly like this:
$email = $assoc["email"];
Remember to ensure that the input contains the email field, just to avoid your error.log unnecessarily spammed.
<?php
function retrieveValueFromNestedList(array $nestedList, $expectedKey)
{
$result = null;
foreach($nestedList as $key => $value) {
if($key === $expectedKey) {
$result = $value;
break;
} elseif (is_array($value)){
$result = $this->retrieveValueFromNestedList($value, $expectedKey);
if($result) {
break;
}
}
}
}

PHP - good practice reading POST variables

I am thinking of a good practice to read the client submitted POST data.
For example if I have a post variable that should have the following structure:
array(
[0] => array(
['test'] => array(1, 2, 3),
['test2'] => "string"
),
[1] => array(
['test'] => array(),
['test2'] => "string2"
),
)
Where the indices 'test' and 'test2' should always be present but their values may be empty (array() and "");
The functions that handle the POST data are expecting the correct format, so I have to make sure that the data has not been manipulated.
I could do the following:
$result = array();
if(isset($_POST['myVar']) && is_array($_POST['myVar'])) {
foreach($_POST['myVar'] as $array) {
$new = array('test' => array(), 'test2' = "");
if(isset($array['test']) && is_array($array['test'])) {
foreach($array['test'] as $expectedInt) {
$new['test'][] = (int)$expectedInt;
}
}
if(isset($array['test2']) && is_string($array['test2']))
$new['test2'] = $array['test2'];
}
$result[] = $new;
}
I think you get the idea what I mean. I wonder if there is a better practice of reading the POST data into the expected format.
I usually do this to assure I have default indices:
$par = $_POST;
$par += [
'key' => 'default',
'other' => 'default',
]
If $par doesn't contain those keys, they are set.
In your case, your could do this:
$ready = [];
foreach($_POST as $k => $v){
$v += [
'test' => [],
'test2' => "string2",
];
// Validate if needed
$v['test'] = (array)$v['test'];
$v['test2'] = (string)$v['test2'];
$ready[$k] = $v;
}
Later you can be sure, that $ready will contain values with test and test2 keys.
This is very useful in functions, where you replace a lot of arguments with one parameter array, and then later set default values,

Updating Associative Arrays

It may just be that I've checked out already for the weekend, but having a bit of trouble updating an associative array based on a certain value. For example, here is what I have so far:
$slideshow_vars = array(
'js_animation' => $slideshow_options['js_animation'],
'js_slide_direction' => $slideshow_options['js_slide_direction'],
'js_slideshow' => $slideshow_options['js_slideshow'],
'js_slideshow_speed' => $slideshow_options['js_slideshow_speed'],
'js_animation_duration' => $slideshow_options['js_animation_duration'],
'js_direction_nav' => $slideshow_options['js_direction_nav'],
'js_control_nav' => $slideshow_options['js_control_nav'],
'js_keyboard_nav' => $slideshow_options['js_keyboard_nav'],
'js_mousewheel' => $slideshow_options['js_mousewheel'],
'js_prev_text' => $slideshow_options['js_prev_text'],
'js_next_text' => $slideshow_options['js_next_text'],
'js_pause_play' => $slideshow_options['js_pause_play'],
'js_pause_text' => $slideshow_options['js_pause_text'],
'js_play_text' => $slideshow_options['js_play_text'],
'js_randomize' => $slideshow_options['js_randomize'],
'js_slide_start' => $slideshow_options['js_slide_start'],
'js_animation_loop' => $slideshow_options['js_animation_loop'],
'js_pause_on_action' => $slideshow_options['js_pause_on_action'],
'js_pause_on_hover' => $slideshow_options['js_pause_on_hover'],
'js_controls_container' => $slideshow_options['js_controls_container'],
'js_manual_controls' => $slideshow_options['js_manual_controls'],
'js_start_function' => $slideshow_options['js_start_function'],
'js_before_function' => $slideshow_options['js_before_function'],
'js_after_function' => $slideshow_options['js_after_function'],
'js_end_function' => $slideshow_options['js_end_function']
);
foreach ($slideshow_vars as $key => $value) {
if($value == NULL) {
$value = "false";
}
}
print_r($slideshow_vars);
In a number of the values in the array, they are outputting NULL -- well, I need to change those to a string of false (this data is being localized and then sent to a JS file which expects false). When I perform the above print_r() it hasn't actually updated anything.
That is because foreach normally passes array fields by value.
What you need to do is this:
foreach ($slideshow_vars as $key => &$value) {
if($value == NULL) {
$value = "false";
}
}
You have to update arrays like this by using the canonical path:
$slideshow_vars[$key] = 'false';
Or what cyper mentioned by using ... as $key => &$value to pass the inner loop the reference of $value instead of just its value.
Each loop, $value is set to the value. By updating the value of $value, you're just changing it in the local scope, and not setting the value inside that array. For that, you want to reference the field and update it, as such:
foreach ($slideshow_vars as $key => $value) {
if($value == NULL) {
$slideshow_vars[$key] = "false";
}
}
If all of the keys are the same and you want to save yourself a lot of code, you could try experimenting with this:
$slideshow_vars = array_merge( // Merge two arrays:
// Create an array of the same keys, but all with values of "false"
array_combine(
array_keys( $slideshow_options),
array_fill( 0, count( $slideshow_options), "false")
),
// Remove values that equal false (may need to specify a more precise callback here)
array_filter( $slideshow_options)
);
This should give you the $slideshow_vars variable you're looking for.

Categories