PHP, set all $_POST to its own named variable - php

on an PHP POST, is there a way of automatically setting each POST variable to its own named variable?
For example if I post
name = "henry"
age = "20"
location = "earth"
Instead of doing:
$name = $_POST['name'];
$age = $_POST['age'];
$location = $_POST['location'];
is there a way of looping through all POST variables and setting it to the same named standard variable?

Extract function can help with this issue:
$_POST = ['foo' => 'bar'];
extract($_POST);
var_dump($foo) //returns 'bar'
http://php.net/manual/en/function.extract.php

It is not recommended to set $_POST variables programmatically. However, if you want it you can use extract function
extract($_POST,EXTR_OVERWRITE,'prefix');

You can be use this:
if ($_POST) {
foreach ($_POST as $key => $value) {
$name = "{$key}";
$$name = $value;
echo "<pre>";
echo $name;
}
echo "<pre>";
echo $name;
echo "<pre>";
echo $age;
echo "<pre>";
echo $location;
}

Related

How to Insert The Values

I have a variable like:
foreach ($array as $data){
$namee=$data['Label_Field'];
${$namee} = $_POST[$namee];
}
How do I get a value like ("data", "data") using those variables?
you can use $$ in php
Example:
$a = 'name';
$$a = 'test';
echo $name;
Result:
test
Example of your code:
foreach ($array as $data){
$namee = $data['Label_Field'];
$$namee = $_POST[$namee];
}
I also suggest you read the following:
https://www.php.net/manual/en/language.variables.variable.php
https://www.geeksforgeeks.org/php-vs-operator/
https://www.javatpoint.com/php-dollar-doubledollar
what is "$$" in PHP
Avoid using variable variables, simply filter $_POST into a new variable, else there is a likely risk of overwriting important variables ($db_connection?).
Instead do some thing like:
<?php
$_POST['foo'] = '';
$_POST['bar'] = '';
$_POST['baz'] = '';
// fields
$fields = [['Label_Field' => 'foo']];
// just labels
$labels = array_column($fields, 'Label_Field');
// filter $_POST by keys which are in $labels
$data = array_filter($_POST, fn($k) => in_array($k, $labels), ARRAY_FILTER_USE_KEY);
print_r($data);
Then use $data['foo'] instead of $foo.
View online: https://3v4l.org/vna02

implode input names from $_POST in php

I am trying to implode inputnames from $_POST with commas and no comma at the end. I have been able to successfuly implode $_POST values but am unable to do the same for inputnames from $_POST. Please help
if(isset($_POST['submit1'])){
$curry = "";
foreach ($_POST as $name => $val)
{
$curry .= $name;
}
echo $curry;
echo implode(",",(array_slice($_POST,0,-2))); //this works for value
echo implode(',',$curry); // this doesnt work for input names
This is because $curry isn't an array which you can implode! It is a string.
So if you change these lines:
$curry = "";
//...
$curry .= $name;
to this:
$curry = array();
//...
$curry[] = $name;
Then it is a array which you can implode.
array_keys() returns an array containing the keys of the input array. You'd use it as follow:
if(isset($_POST['submit1'])){
echo implode(",",(array_slice($_POST,0,-2)));
echo implode(',',(array_slice(array_keys($_POST),0,-2)));

print name using for loop php

Using for loop in PHP can we have numbers associate with a variable name?
ex:
$name1="hi";
$name2="khj";
for($i=0;$i<=2;$i++)
{
echo ..
}
How can we print $name1 and $name2 using for loop?
Thanks!
Yes this is called variable interpolation.
$name1="hi";
$name2="khj";
for($i=1;$i<=2;$i++) {
$var = 'name' . $i;
echo $$var;
}
Note: There are multiple syntaxes for variable interpolation in PHP. Also, I modified your loop to start at 1.
for($i = 1; $i <= 2; $i++)
{
echo $name{$i};
}
It would be way easier to put it in an array though, that's what we have them for.
$names = array();
$names[1] = 'A';
$names[2] = 'B';
foreach($names as $name)
{
echo $name;
}
put this in the for loop:
echo ${'name'.$i}."\n";
Better to use something like:-
$names[] = $name1;
$names[] = $name2;
foreach($names as $name){
echo $name;
}
This print the name1 and name2 .And i value must be start from 1
for($i=1;$i<=2;$i++)
{
echo ${'name'.$i}."<br>";
}

php loop statement question

I'm wondering if it is possible to loop a variable within a variable? Here is something I want to setup:
$var1 = Benjamin
$var2 = George
$var3 = Abraham
and probably echo out something like
<li>Benjamin</li>
<li>George</li>
<li>Abraham</li>
but I want to know, if I want to add $var4 = ..., $var5 = ..., is there a way I can do this all in a loop? I'm thinking having an empty() function that'll loop the variable names/numbers until reaches the first empty variable?
You could store them in an array.
$names = array('Mike', 'Jim', 'Tom', 'Stacy');
foreach($names as $name){
echo $name;
}
As seen here: http://www.ideone.com/f7Ce7
In PHP you can do this:
$var1 = "foo";
$var2 = "bar";
$name = "var1";
$i=1;
while( !is_null( $$name ) ) {
echo '<li>' . $$name . '</li>';
$i++;
$name = "var$i";
}
but a better solution may be using an array and a foreach
This sounds like you want to use arrays and foreach. Am I missing something?
$presidents = array(
'Benjamin', 'George', 'Abraham'
);
foreach($presidents as $pres) {
echo "$pres\n";
}
$var=array('Benjamin', 'George', 'Abraham');
foreach ($var as $name){
echo $name;
}
A better solution would be arrays.
define it as:
$names = array(0=>"Benjamin",1=>"George",2=>"Abraham");
Then loop through it with:
foreach ($names as $id=>$name)
{
echo $name;
}
Then reference a name with $names[0], if you want to add another use $names[] = 'William';
Look up more information at:http://php.net/manual/en/language.types.array.php
This solution doesn't require the use of an array.
$var1 = 'Benjamin';
$var2 = 'George';
$var3 = 'Abraham';
//add as many variables as you want
$i = 0;
$currentVariable = 'var'.$i;
while (isset($$currentVariable)) {
//process variable
echo $$currentVariable;
$i++;
}

php string name as variable

$string = "id";
want result to be like
$id = "new value";
How do I code this in php?
Edit..
How about the below?
$column = array("id","name","value");
let say found 3 row from mysql
want result to be like this
$id[0] = "3";
$id[1] = "6";
$id[2] = "10";
$name[0] = "a";
$name[1] = "b";
$name[2] = "c";
$value[0] = "bat";
$value[1] = "rat";
$value[2] = "cat";
Theres 2 main methods
The first is the double $ (Variable Variable) like so
$var = "hello";
$$var = "world";
echo $hello; //world
//You can even add more Dollar Signs
$Bar = "a";
$Foo = "Bar";
$World = "Foo";
$Hello = "World";
$a = "Hello";
$a; //Returns Hello
$$a; //Returns World
$$$a; //Returns Foo
$$$$a; //Returns Bar
$$$$$a; //Returns a
$$$$$$a; //Returns Hello
$$$$$$$a; //Returns World
//... and so on ...//
#source
And the second method is to use the {} lik so
$var = "hello";
${$var} = "world";
echo $hello;
You can also do:
${"this is a test"} = "works";
echo ${"this is a test"}; //Works
I had a play about with this on streamline objects a few weeks back and got some interesting results
$Database->Select->{"user id"}->From->Users->Where->User_id($id)->And->{"something > 23"};
You are looking for Variable Variables
$$string = "new value";
will let you call
echo $id; // new value
Later in your script
Second answer in response to your edit:
$result = mysql_query($sql);
$num = mysql_num_rows($result);
$i = 0;
$id = array();
$name = array();
$value = array();
if ($num > 0) {
while ($row = mysql_fetch_assoc($result)) {
$id[$i] = $row['id'];
$name[$i] = $row['name'];
$value[$i] = $row['value'];
$i++;
}
}
This loops around your result, using the counter $i as the key for your result arrays.
EDIT
Additional answer in response to your comment:
while ($row = mysql_fetch_assoc($result)) {
foreach($row as $column_name => $column_value) {
$temp_array[$column_name][$i] = $column_value;
}
$i++;
}
foreach ($temp_array as $name => $answer) {
$$name = $answer;
}
This code creates a temporary multidimensional array to hold the column names and values the loops around that array to create your variable variable arrays. As a side not I had to use the temp array as $$column_name[$i] doesn't work, I would love to see alternative answers to this problem.
Final note #Paisal, I see you have never accepted an answer, I wouldn't have put this much effort in if I had seen that before!
You can do this
$$string = "new value";
juste double $
Are you referring to variable variables?
That would accomplish something like this:
$string = "id";
$$string = "new value";
This produces a variable $id with the value "new value".
Don't do that. Just use an array.
$arr[$string] = 'new value';
ref: How do I build a dynamic variable with PHP?
Try this :
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);
$i = 0;
if ($num_rows) {
while ($row = mysql_fetch_assoc($result)) {
foreach($row AS $key => $value) {
${$key}[$i] = $value;
}
$i++;
}
}
For those of us who need things explained in great detail...
// Creates a variable named '$String_Variable' and fills it with the string value 'id'
$String_Variable = 'id';
// Converts the string contents of '$String_Variable', which is 'id',
// to the variable '$id', and fills it with the string 'TEST'
$$String_Variable = 'TEST';
// Outputs: TEST
echo $id;
// Now you have created a variable named '$id' from the string of '$String_Variable'
// Essentially: $id = 'Test';

Categories