PHP foreach set row name as new variable - php

My Php function loops trough the mysql table and for each row it sets the row name as $var and the row value to $val.
foreach($row as $var => $val) {...
Now I want to set the received rowname ($var) as a new variable.
This example is not right but to explain my thoughts ; $name$var = $val
If $var would be = rowname1
then the new variable would be $rowname1 = value1
Any ideas how to achieve this ?
Thanks.

You can use variable variables to do that:
foreach(...) {
$$var = $val;
}
But cleaner would be to use an array:
foreach(...) {
$var_names[] = array($var => $val);
}

<?php
$array = array(
'go' => 'something1',
'go2' => 'something2',
'go3' => 'something3',
'go4' => 'something4',
'go5' => 'something5',
);
foreach ($array as $key => $val) {
${$key} = $val;
}
print $go;
?>
EXAMPLE
or you could use the $$ way explained here:
Read more about Variable Variables...

You can use it like ${$var} = $val. Curly brackets are there just for convenience and readability. $$var = $val should also work.

You can create variables with dynamic names on the fly using strings! This is supported in the documentation provided here
A quick example:
// This now holds the string hello
$variableName = 'hello';
// This creates the variable 'hello' and contains the value test
$$variableName = "test";
echo $hello;
With the above example complete you will be able to create a variable name with the key + value strings as follows:
$count = 1;
foreach($row as $var => $val)
{
$varName = $var.$count;
$$varName = $val;
$count++;
}
This will create column_name1, column_name2 etc.
I feel the need to add a little discretion as this is not common or best practice. The best way to handle this information would be to take the $key => $val pair and store it into a separate variable or parse through them. By doing this you are basically throwing away all of the ease of use that is using arrays.
Also, side note:
You can also dynamically call on methods this way.
function test()
{
echo "test yar";
}
$method = "test";
$method();

Related

PHP dynamic array name with loop

I need to get values of array through a loop with dynamic vars.
I can't understand why the "echo" doesn’t display any result for "$TAB['b']".
Do you know why ?
The test with error message : https://3v4l.org/Fp3GT
$TAB_a = "aaaaa";
$TAB['b'] = "bbbbb";
$TAB['b']['c'] = "ccccc";
$TAB_paths = ["_a", "['b']", "['b']['c']"];
foreach ($TAB_paths as $key => $value) {
echo "\n\n\${'TAB'.$value} : "; print_r(${'TAB'.$value});
}
You are treating the array access characters as if they are part of the variable name. They are not.
So if you have an array $TAB = array('b' => 'something');, the variable name is $TAB. When you do ${'TAB'.$value}, you're looking for a variable that's actually named $TAB['b'], which you don't have.
Since you say that you just want to be able to access array indexes dynamically based on the values in another array, you just put the indexes alone (without the array access characters) in the other array.
$TAB['b'] = 'bbbbbb';
$TAB['c'] = 'cccccc';
$TAB_paths = array('b', 'c');
foreach ($TAB_paths as $key => $value) {
echo "\n\n".'$TAB['."'$value'".'] : ' . $TAB[$value];
}
Output:
$TAB['b'] : bbbbbb
$TAB['c'] : cccccc
DEMO
It's unclear what you're trying to do, although you need to include $TAB_all in $TAB_paths:
$TAB_paths = [$TAB_all['a'], $TAB_all['aside']['nav']];
Result:
${TAB_all.aaaaa} : ${TAB_all.bbbbb} :
Not certain what you're needing. My guess you need to merge two arrays into one. Easiest solution is to use the array_merge function.
$TAB_paths = array_merge($TAB_a1, $TAB_a2);
You can define the variable first
foreach ($TAB_all as $key => $value) {
${"TAB_all" . $key} = $value;
}
Now Explore the result:
foreach ($TAB_all as $key => $value) {
print_r(${"TAB_all" . $key});
}

Are different PHP variable variables that resolve to the same variable name the same variable?

Let's say I have an array of strings that I use to create variable variables:
$var_arr = ["item1", "item2", "item3"];
foreach ($var_arr as $item) {
$$item = array();
}
Then elsewhere in my code I have to recreate the variable variable based on a different data source:
$user_input = [ "prod1" => "widget", "qty1" => 3, "prod2" => "thingy", "qty2" => 1, "prod3" => "dingus", "qty3" => 7 ];
foreach ($user_input as $key => $value) {
$a = "item" . substr($key, -1);
array_push($$a, $value);
}
Are $$item and $$a the same variable, or do they reference different blocks of memory?
Both are the same what you need to consider here is that you are just referencing a variable through each assignment here:
<?php
$hello ="hello in variable";
$array_hello = ["hello","Yellow"];
$hello_var = "hello";
$item = $array_hello[0];
echo $$hello_var;
echo $$item; //result same as above result
?>
Here one thing to notice is ${$variable_name_string} is just using $variable_name_string to know the name of the variable you want so both will be accessing the same memory block because you are referencing same variable here.
One more thing to notice here is the change in interpretation in PHP 7 from PHP 5
Expression $$foo['bar']['baz'] PHP 5 interpret it as ${$foo['bar']['baz']} while PHP 7 interpret it as ($$foo)['bar']['baz']
Refer PHP manual for more

Put each value of an array in a new variable in PHP

I have an array composed of files of a folder.
When I use the following snippet :
foreach($myarray as $key => $value)
{
echo $value. "<br>";
}
I have the following output :
vendor/templates/File1.docx
vendor/templates/File2.docx
vendor/templates/File3.docx
My question is : how to make it to put each value of my array in a new variable ? How to make it automatically if I have e.g 100 files in my folder ?
Actually I'd like to have (if my array is only composed of 3 items) :
$a = 'vendor/templates/File1.docx'
$b = 'vendor/templates/File2.docx'
$c = 'vendor/templates/File3.docx'
I guess I should use a loop but after many tests, I'm still getting stuck..
Have you any ideas ?
Thanks !!
Here is the solution:
<?php
$myarray = ['vendor/templates/File1.docx', 'vendor/templates/File2.docx', 'vendor/templates/File3.docx'];
foreach($myarray as $key => $value)
{
$varname = "var".$key;
$$varname = $value;
}
echo $var0."\n";
echo $var1."\n";
echo $var2."\n";
->
vendor/templates/File1.docx
vendor/templates/File2.docx
vendor/templates/File3.docx
May be following function will work for your problem.
extract($array);
http://php.net/extract

How to separate and assign data in a multi dimensional array via a loop - PHP

I have an associative array of data coming from another script:
while($row = mysqli_fetch_assoc($query)){
$replyArray[] = array(
'did' => $row['discussion_id'],
'rid' => $row['reacter_id'],
'reply' => $row['reply'],
'date' => $row['date']
);
}
I have a function that will use this array $replyArray:
//In this function we extract data(discussions) from array
//This function is called inside disReply function.
function subDiscussion($replyArray){
$reply_count = count($replyArray);
for($x=0; $x < $reply_count; $x++){
echo "<br><h3>Data: ".($x +1).' <br>'."</h3>" ;
foreach($replyArray[$x] as $key => $value){
echo $data= $key.": ". $value."<br>";
}
}
};
The example above returns all associated paired data by just echoing the variable $data.
What I want to achieve is to separate the data(data in paire) into different variables:
$rid = its value
$did = its value
$reply = its value
$date = its value
The reason is because I want to put them in an HTML design in that function later.
Thank you.
Variable variables will help here:
// inside the final (foreach) loop
foreach($replyArray[$x] as $key => $value){
$$key = $value;
}
// now use these variables, $did, $rid, etc., e.g. save to an array or use in a function - else they will be overwritten in next iteration of parent for loop
Read more about variable variables here.
According to what Patrick Q suggested using the PHP extract()
for($x=0; $x < $reply_count; $x++){
extract($replyArray[$x]);
}
extract() This function treats keys as variable names and values as variable values. For each key/value pair it will create a variable

creating variable names from an array list

How can I dynamically create variable names based on an array? What I mean is I want to loop through this array with a foreach and create a new variable $elem1, $other, etc. Is this possible?
$myarray = array('elem1', 'other', 'elemother', 'lastelement');
foreach ($myarray as $arr){
//create a new variable called $elem1 (or $other or $elemother, etc.)
//and assign it some default value 1
}
foreach ($myarray as $name) {
$$name = 1;
}
This will create the variables, but they're only visible within the foreach loop. Thanks to Jan Hančič for pointing that out.
goreSplatter's method works and you should use that if you really need it, but here's an alternative just for the kicks:
extract(array_flip($myarray));
This will create variables that initially will store an integer value, corresponding to the key in the original array. Because of this you can do something wacky like this:
echo $myarray[$other]; // outputs 'other'
echo $myarray[$lastelement]; // outputs 'lastelement'
Wildly useful.
Something like this should do the trick
$myVars = Array ();
$myarray = array('elem1', 'other', 'elemother', 'lastelement');
foreach ($myarray as $arr){
$myVars[$arr] = 1;
}
Extract ( $myVars );
What we do here is create a new array with the same key names and a value of 1, then we use the extract() function that "converts" array elements into "regular" variables (key becomes the name of the variable, the value becomes the value).
Use array_keys($array)
i.e.
$myVars = Array ();
$myarray = array('elem1', 'other', 'elemother', 'lastelement');
$namesOfKeys = array_keys($myVars );
foreach ($namesOfKeys as $singleKeyName) {
$myarray[$singleKeyName] = 1;
}
http://www.php.net/manual/en/function.array-keys.php

Categories