Get the names of $_POST variables by value - php

If I have several post results that are like this:
$_POST["ResponseA"] = 1, $_POST["ResponseB"] = 1, $_POST["ResponseC"] = 2, $_POST["ResponseD"] = 3, $_POST["ResponseE"] = 1, etc.
How can I perform a loop that gets an array based upon the values? So If I'm checking for a value of 1, I get ResponseA, ResponseB, ResponseE ?

<?php
$results = array_keys($_POST, 1);
var_dump($results);
?>

Use array_flip() like this...
$flipped = array_flip($_POST);
echo $flipped['1']; // ResponseA
You will get issues doing this though as your values are not unique

simple build a loop
<?php
$fields = array('ResponseA','ResponseB','ResponseC','ResponseD','ResponseE')
function searchValue(array $fields, $value) {
$out = array();
foreach($fields as $name) {
if(isset($_POST[$name]) && $_POST[$name] == $value) $out[]=$name;
}
return $out;
}
var_dump(searchValue($fields,1));

You can loop through the $_POST:
foreach ($_POST as $key => $value) {
if ($value == 1) {
// $key will equal the value ResponseA if $_POST["ResponseA"] = 1
}
}

Related

Storing only certain $_GET request values

Currently I have this code that stores all $_GET requests:
$array_name = array();
foreach ($_GET as $key => $value) {
$array_name[] = "'%".escape_string($value)."%'";
}
My goal is to somehow only store certain values, if for example I have 5 different $_GET request, named 1,2,3,4 and 5. I only want to store 1-3 in this array. How would this be possible?
$array_name = array();
foreach ($_GET as $key => $value) {
if(in_array($key, array(1, 2, 3)))
$array_name[] = "'%".escape_string($value)."%'";
}
}
It this what you are looking for?
You can get the intersection of an array of keys you want:
foreach(array_intersect_key($_GET, array_flip([1,2,3])) as $value) {
$array_name[] = "'%".escape_string($value)."%'";
}
Slightly different approach to the other answers. $keysToStore is an array of the keys you want to store.
The foreach loop then pulls these values from the $_GET array rather than looping the entire array.
$keysToStore = [1, 2, 3];
$array_name = [];
foreach ( $keysToStore as $key ) {
$array_name[] = "'%" . escape_string( $_GET[$key] ) . "%'";
}
Edit: can check isset inside the loop if keys are not validated elsewhere.
$keysToStore = [1, 2, 3];
$array_name = [];
foreach ( $keysToStore as $key ) {
if ( isset( $_GET[$key] ) ) {
$array_name[] = "'%" . escape_string( $_GET[$key] ) . "%'";
}
}
For this, you need to add check on $key, that $key has value 1 or 2 or 3. Sample code is this:
$array_name = array();
foreach ($_GET as $key => $value) {
if($key == '1' || $key == '2' || $key == '3'){
$array_name[] = "'%".escape_string($value)."%'";
}
}
Or the other sample code is:
$array_name = array();
foreach ($_GET as $key => $value) {
if(in_array($key, array(1, 2, 3))){
$array_name[] = "'%".escape_string($value)."%'";
}
}
Here 1 , 2 and 3 is key of $_GET. Sample input is: $_GET['1'] = 'Ghazal' , $_GET['2'] = 'Taimur' , $_GET['3'] = 'Malik' , $_GET['4'] = 'Test' , $_GET['5'] = 'City'

Getting formatted result with nested arrays in PHP

I am trying to generate sql statement dynamically with loops but i am not getting any idea on how to do it with html name array.
assuming $name and $message are post arrays ... and assuming length of both will be equal,
following is a method i tried;
<?php
$name = array('name1','name2' );
$mess= array('message1','message2' );
$values = array($name,$mess);
foreach ($values as $key){
foreach ($key as $value){
echo $value.",";
}
}
?>
output is =
name1,name2,message1,message2,
but i want output as =
(name1,message1),(name2,message2),
Edit : I have acess to $values only and I will not be able to determine how many values are going to join in $values ..
like it can be
$values=array($name,$message,$phone);
and the result i want will be
(name1,message1,phone1),(name2,message2,phone2)
My solutions is
Step 1: Loop your $values this will gonna loop every index of your array like $name
foreach($name as $index => $value) {
// do something
}
Step 2: Inside your loop values start with ( which mean wrap your detail in (
echo "(";
Step 3: loop parent array
foreach($values as $key => $arr) {
// do something
}
Step 4: Inside the loop of your parent array display each data according to your index
echo $values[$key][$index];
$key represents the index of your parent array while $index represents the index of your child array like $name
this loop will create data like
(name1,message1,phone1)
and I just add this
if ($key < sizeof(array_keys($values))-1) {
echo ",";
}
to avoid adding , after the last loop
This code will dynamically display array you put inside $values
So your code would be like this
$name = array('name1','name2','name3','name4' );
$mess= array('message1','message2','message3','message4' );
$phone= array('phone1','phone2','phone3','phone4' );
$married= array('yes','no','yes','yes' );
$values = array($name,$mess,$phone);
foreach($name as $index => $value) {
echo "(";
foreach($values as $key => $arr) {
echo $values[$key][$index];
if ($key < sizeof(array_keys($values))-1) {
echo ",";
}
}
echo "),";
}
Demo
or this
$name = array('name1','name2','name3','name4' );
$mess= array('message1','message2','message3','message4' );
$phone= array('phone1','phone2','phone3','phone4' );
$values = array($name,$mess,$phone);
foreach($name as $index => $value) {
$join = array();
foreach($values as $key => $arr) {
$join[] = $values[$key][$index];
}
echo "(".implode(",",$join)."),";
}
Demo
$name = array('name1','name2' );
$mess = array('message1','message2' );
foreach ($names as $k => $v){
echo "(".$v.",".$mess[$k]."),";
}
Try this, you not need two foreach loop, only use foreach loop and pass key to other array and get value
$name = array('name1','name2' );
$mess= array('message1','message2' );
$values = array($name,$mess);
foreach ($name as $keys => $vals)
{
echo "(".$vals.",".$mess[$keys]."),";
}
DEMO
You can use arrap_map() function in order to join two array. Here is reference http://php.net/manual/en/function.array-map.php
<?php
$name = array('name1','name2' );
$mess= array('message1','message2' );
$value = array_map(null, $name, $mess);
print_r($value);
?>

Compare and replace values in array

I need compare 2 arrays , the first array have one order and can´t change , in the other array i have different values , the first array must compare his id with the id of the other array , and if the id it´s the same , take the value and replace for show all in the same order
For Example :
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
The Result in this case i want get it´s this :
"1a-dogs","2a-cats","3a-birds","4a-walking"
If the id in this case 4a it´s the same , that entry must be modificate and put the value of other array and stay all in the same order
I do this but no get work me :
for($fte=0;$fte<count($array_1);$fte++)
{
$exp_id_tmp=explode("-",$array_1[$fte]);
$cr_temp[]="".$exp_id_tmp[0]."";
}
for($ftt=0;$ftt<count($array_2);$ftt++)
{
$exp_id_targ=explode("-",$array_2[$ftt]);
$cr_target[]="".$exp_id_targ[0]."";
}
/// Here I tried use array_diff and others but no can get the results as i want
How i can do this for get this results ?
Maybe you could use the array_udiff_assoc() function with a callback
Here you go. It's not the cleanest code I've ever written.
Runnable example: http://3v4l.org/kUC3r
<?php
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
function getKeyStartingWith($array, $startVal){
foreach($array as $key => $val){
if(strpos($val, $startVal) === 0){
return $key;
}
}
return false;
}
function getMergedArray($array_1, $array_2){
$array_3 = array();
foreach($array_1 as $key => $val){
$startVal = substr($val, 0, 2);
$array_2_key = getKeyStartingWith($array_2, $startVal);
if($array_2_key !== false){
$array_3[$key] = $array_2[$array_2_key];
} else {
$array_3[$key] = $val;
}
}
return $array_3;
}
$array_1 = getMergedArray($array_1, $array_2);
print_r($array_1);
First split the 2 arrays into proper key and value pairs (key = 1a and value = dogs). Then try looping through the first array and for each of its keys check to see if it exists in the second array. If it does, replace the value from the second array in the first. And at the end your first array will contain the result you want.
Like so:
$array_1 = array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2 = array("4a-walking","2a-cats");
function splitArray ($arrayInput)
{
$arrayOutput = array();
foreach ($arrayInput as $element) {
$tempArray = explode('-', $element);
$arrayOutput[$tempArray[0]] = $tempArray[1];
}
return $arrayOutput;
}
$arraySplit1 = splitArray($array_1);
$arraySplit2 = splitArray($array_2);
foreach ($arraySplit1 as $key1 => $value1) {
if (array_key_exists($key1, $arraySplit2)) {
$arraySplit1[$key1] = $arraySplit2[$key1];
}
}
print_r($arraySplit1);
See it working here:
http://3v4l.org/2BrVI
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
function merge_array($arr1, $arr2) {
$arr_tmp1 = array();
foreach($arr1 as $val) {
list($key, $val) = explode('-', $val);
$arr_tmp1[$key] = $val;
}
foreach($arr2 as $val) {
list($key, $val) = explode('-', $val);
if(array_key_exists($key, $arr_tmp1))
$arr_tmp1[$key] = $val;
}
return $arr_tmp1;
}
$result = merge_array($array_1, $array_2);
echo '<pre>';
print_r($result);
echo '</pre>';
This short code works properly, you'll get this result:
Array
(
[1a] => dogs
[2a] => cats
[3a] => birds
[4a] => walking
)

show only duplicate values from array without builtin function PHP

For example:
$arr = array(3,5,2,5,3,9);
I want to show only common elements i.e 3,5 as output.
Here's my attempt:
<?php
$arr = array(3,5,2,5,3,9);
$temp_array = array();
foreach($arr as $val)
{
if(isset($temp_array[$val]))
{
$temp_array[$val] = $val;
}else{
$temp_array[$val] = 0;
}
}
foreach($temp_array as $val2)
{
if($val2 > 0)
{
echo $val2 . ', ';
}
}
?>
--
Output --
3, 5,
Try the following:
$arr = array(3,5,2,5,3,9);
foreach($arr as $key => $val){
//remove the item from the array in order
//to prevent printing duplicates twice
unset($arr[$key]);
//now if another copy of this key still exists in the array
//print it since it's a dup
if (in_array($val,$arr)){
echo $val . " ";
}
}
Output:
3 5
Addition:
I guess that the reason you were asked to implement it yourself (without using built-in functions) was to avoid answers like:
$unique = array_unique($arr);
$dupes = array_diff_key( $arr, $unique );
$arrnew = array();
for($i=0;$i<count($arr);$i++)
{
for($j=$i+1;$j<count($arr);$j++)
{
if($arr[$i]==$arr[$j])
{
$arrnew[]=$arr[$j];
}
}
}

Looping associated cookies and storing them in array in PHP

I have a small script that sets multiple cookies, they all have this format item_1928 item_3847 item_5782 etc.
I need to get all the values for the cookies that start with item and store them in an array.
Here's is some code I found on SO but I'm not sure it's what I'm looking for. It just stores the key, but not the values:
$matches = array();
foreach($_COOKIE as $key => $value) {
if(substr($key, 0, 20) == 'wordpress_logged_in_') {
$matches[] = $key;
}
}
You can try this:
foreach($_COOKIE as $key => $value) {
if(strstr($key ,"item_")) {
$matches[$key] = $value;
}
}
You should be able to modify that code like this:
$matches = array();
$values = array();
foreach($_COOKIE as $key => $value) {
if(substr($key, 0, 20) == 'wordpress_logged_in_') {
$matches[] = $key;
$values[] = $_COOKIE[$key];
}
}
Then you'll have all the values (and NOT the keys) in the $values array.

Categories