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
Related
This is my current code, I'm looking for a more efficient way of writing it.
Need something like looping through each variable with a foreach or adding them all to an array somehow, without me having to re-write every variable name.
$formValues = $form_state->getValues();
$relocation = $formValues['relocation'];
$europe = $formValues['europe'];
$twoyears = $formValues['twoyears'];
$realestate = $formValues['realestate'];
$nominated = $formValues['check_nominated_by'];
$nom_comp = $formValues['nom_company'];
$nom_contact = $formValues['nom_contact'];
$nom_email = $formValues['nom_email'];
$contact1 = $formValues['contact1'];
$position1 = $formValues['contact_position1'];
$email1 = $formValues['email1'];
$contact2 = $formValues['contact2'];
$position2 = $formValues['contact2'];
$email2 = $formValues['contact2'];
$contact3 = $formValues['contact3'];
$position3 = $formValues['contact3'];
$email3 = $formValues['contact3'];
tempstore = array();
$tempstore['relocation'] = $relocation;
$tempstore['europe'] = $europe;
$tempstore['twoyears'] = $twoyears;
$tempstore['realestate'] = $realestate;
$tempstore['membertype'] = $membertype;
$tempstore['nominated_by'] = '';
// All other fields need to be in this array too
// But there are a lot of unwanted fields in the $formValues
$_SESSION['sessionName']['formName'] = $tempstore;
Seeing as you know the keys you'd like to keep you can do the following:
<?php
/** The keys you want to keep... **/
$keys_to_keep = [
];
/** Will be used to store values for saving to $_SESSION. **/
$temp_array = [];
/** Loop through the keys/values. **/
foreach ($formValues as $key => $value) {
/** The correct key i.e. the key you'd like to save. **/
if (in_array($key, $keys_to_keep)) {
/** What you wish to do... **/
$temp_array[$key] = $value;
}
}
$_SESSION['sessionName']['formName'] = $temp_array;
?>
What is happening is that you are looping through your $formValues and getting both the keys and values of each pair in the array.
Then an check is being done against your $keys_to_keep to see if the current element is the one you wish to keep, if it is then you save it in to $temp_array.
Reading Material
foreach
in_array
You can use variable variables and a foreach.
Foreach($formValues as $key => $var){
$$key = $var;
}
Echo $relocation ."\n" . $europe;
https://3v4l.org/QeLjp
Edit I see now that your array variable keys are not always the same as the variable name you want.
In that case you can't use the method above.
In that case you need to use list() = array.
List($relocation, $europe) = $formValues;
// The list variables have to be in correct order I just took the first two for demo purpose.
Is it possible to do this without having to type the entire thing?
Like with a foreach loop that generates the required variable names from the session variable names?
if (isset($_SESSION['MembershipForm'])) {
$tempstore = $_SESSION['MembershipForm'];
if (isset($tempstore['ref_referee'])) {
$ref_referee = $tempstore['ref_referee'];
} else {
$ref_referee = NULL;
}
if (isset($tempstore['ref_address'])) {
$ref_address = $tempstore['ref_address'];
} else {
$ref_address = NULL;
}
}
You can use extract() function:
$tempstore = $_SESSION['MembershipForm'];
extract($tempstore);
echo $ref_referee;
Well... if I understand you correctly you have something like:
$_SESSION['MembershipForm'] = array('key1' => 'value1', 'key2' => 'value2'); // etc
And you want to create dynamic variables depending on the content of your array.
foreach($_SESSION['MembershipForm'] as $key => $value){
${$key} = $value;
// this will create variables like this $key1 = 'value1'; etc
}
What happen if it is a very big array? One would try to save memory. The next example makes copies of parts of the array, but it should be not necessary, since the array is a global variable.
function arrayTraverse($key) {
global $someArray;
$keys = func_get_args();
$arrayPart = $someArray;
foreach ($keys as $key) {
$arrayPart = $arrayCopy[$key];
}
$value = $arrayPart;
return $value;
}
Usage example:
$someArray = [];
$someArray['aKey'] = [];
$someArray['aKey']['someOtherKey'] = [];
$someArray['aKey']['someOtherKey'][5] = [];
$someArray['aKey']['someOtherKey'][5]['value'] = 'hello';
echo arrayTraverse('aKey', 'someOtherKey', 5, 'value'); // hello
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++;
}
how take string from array define as new array,
how to code in php
$column = array("id","name","value");
let say found 3 row from mysql
want result to be like this
$id[0] = "1";
$id[1] = "6";
$id[2] = "10";
$name[0] = "a";
$name[1] = "b";
$name[2] = "c";
$value[0] = "bat";
$value[1] = "rat";
$value[2] = "cat";
I want to take string from $column array define as new array.
how to code it?
or if my question is stupid , my please to have suggestion.
thank you.
Answer I made on your previous question:
$result = mysql_query($sql);
$num = mysql_num_rows($result);
$i = 0;
if ($num > 0) {
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;
}
}
I can't see why you'd want to model your data like this, you're asking for a world of hurt in terms of debugging. There are "variable variables" you could use to define this, or build global variables dynamically using $GLOBALS:
$somevar = "hello"
$$somevar[0] = "first index"; // creates $hello[0]
$GLOBALS[$somevar][0] = "first index"; // creates $hello[0] in global scope
try
$array = array();
foreach ($results as $r){
foreach ($column as $col ){
$array[$col][] = $r[$col];
}
}
extract ($array);
or you can simply do this
$id = array();
$name = array();
$value = array();
foreach ( $results as $r ){
$id[] = $r['id']; // or $r[0];
$name[] = $r['name'];
$value[] = $r['value'];
}
Hope this is what you asked
This is pretty dangerous, as it may overwrite variables you consider safe in your code. What you're looking for is extract:
$result = array();
while ($row = mysql_fetch_array($result))
foreach ($column as $i => $c)
$result[$c][] = $row[$i];
extract($result);
So, if $result was array( 'a' => array(1,2), 'b' => array(3,4)), the last line defines variables $a = array(1,2) and $b = array(3,4).
You cannot use variable variables right on for this, and you shouldn't anyway. But this is how you could do it:
foreach (mysql_fetch_something() as $row) {
foreach ($row as $key=>$value) {
$results[$key][] = $value;
}
}
extract($results);
Ideally you would skip the extract, and use $results['id'][1] etc. But if you only extract() the nested array in subfunctions, then the local variable scope pollution is acceptable.
There is no need for arrays or using $_GLOBALS, i believe the best way to create variables named based on another variable value is using curly brackets:
$variable_name="value";
${$variable_name}="3";
echo $value;
//Outputs 3
If you are more specific on what is the array you receive i can give a more complete solution, although i must warn you that i have never had to use such method and it's probably a sign of a bad idea.
If you want to learn more about this, here is a useful link:
http://www.reddit.com/r/programming/comments/dst56/today_i_learned_about_php_variable_variables/