Put each value of an array in a new variable in PHP - 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

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});
}

foreach to a link

I have a problem.
I have written a web site where there are two PHP files where 1st contains variables and one array and next one contains next array with variables. Variables of second file are url adress. And now I need to know, if I can make something like:
with foreach
foreach($array01 as $word) {
$a = 0;
echo '<a href="'. $array_url[$a] .'><li>'.$word.'</li></a>';
$a = $a + 1;``
}
Output:
<li>var01</li>
<li>var02</li>
with foreach:
foreach ($array01 as $word) {
$a = 0;
echo '<li>'.$word.'</li>';
$a = $a + 1;
}
I know it does not works with this example but maybe there is a way to make it correct.
The problem in your code is that you're doing $a = 0; at the beginning of each loop. That undoes the $a = $a + 1; that you do at the end, so you're using $array_url[0] every time. You can fix that by putting $a = 0; before the loop instead of inside it.
But instead, you can tell foreach to give you the array indexes as well as the values. Then you can use that index to access the other array.
foreach ($array01 as $i => $word) {
echo '<a href="'. $array_url[$i] .'><li>'.$word.'</li></a>';
}
your question is unclear, you must specify your arrays
BUT
i think you should use for instead of foreach
for($a=0; $a < count($array01); $a++)
{
echo '<a href="'. $array_url[$a] .'><li>'.$array01[$a].'</li></a>';
}
What your asking is unclear but as I've understood from your question, you want to take an array of urls from a PHP file into another PHP file and output them as link in the HTML format.
If that's the case then follow this:
Your 2nd PHP file should look like this as far as I can guess::
<?php
//some codes..
$arrayofvariables=["word" => "url_address",....]; //your array of url address
//some codes..
?>
And in your 1st file do something like this::
<?php
include 'pathtoyour2ndfile'; // include your 2nd file with url array
foreach($arrayofurladdress as $word => $url_address){
echo "<li>$word</li>";
}
I could not figure what is the use of the variables and array in the first file. So, If this isn't what you're looking for please try to clarify your question by improving your English or upload all the content of your PHP files in the question.
Thanks. And A Happy New Year 2016. Hope my answer helps you. If it does don't forget to rate it and mark as answer.
Try This
$a = 0;
foreach ($array01 as $word) {
echo '<li>'.$word.'</li>';
$a++;
}
if your $array_url is like
$array_url = [ 'var_url01' , 'var_url02', 'var_url03'] ;
and your $array01 is like
$array01 = [ 'var01' , 'var02' , 'var03'];
then you can use the foreach loop as
foreach ($variable as $key => $value) {
echo '<li>'.$word.'</li>';
}

php constant gets duplicated inside foreach loop

I've been strugling with this problem for some time now. I can't figure out whats wrong.
Following code is very simple, VISOR_URL is a constant defined in another file. If i echo it outside forearch loop it prints the constant value. If I print it inside the loop it's value gets duplicated.
Same problem occurs if I use a variable.
Any ideas?.
Thanks in advance.
Sebastian
<?php
require_once('conf.php');//I require the file where VISOR_URL is defined
//VISOR_URL is defined in conf.php. define('VISOR_URL', $server_ip.'/'.VISOR_NAME);
echo VISOR_URL; //echoes http://192.168.0.15/tncvisornuevo
if (!empty($occurrence_ids)) {//occurrence_ids is an array and values are printed fine
foreach ($occurrence_ids as $key => $value) {
echo VISOR_URL; //echoes http://192.168.0.15/tncvisornuevohttp://192.168.0.15/tncvisornuevo
$ocurrencia = new ca_occurrences($value);
$nombre_ocurrencia = $ocurrencia->get('ca_occurrences.preferred_labels');
$link = ''.$nombre_ocurrencia.'';
echo $link."<br>";
}
}
?>
Following simple example does not duplicate the constant value:
<?php
//Define a constant
define('CONSTANT', 'imaconstant');
echo CONSTANT."<br>"; //Echoes imaconstant
$test_array = array(0,1,2,3,4,5,6,7,8);
foreach ($test_array as $key => $value) {
echo $value.CONSTANT,"<br>"; //Echoes nimaconstant, n+1imaconstant
}
?>
It'll echo it as many times the loop will run. For example -
$array = array('aa','bb','cc');
$var = "abc";
foreach($array as $key => $value);
{
echo $var.'<br>';
}
/*
abc
abc
abc
*/
Now above since the array has size of 3, the loop will run 3 times and echoes the variable...ofcourse 3 times.

Stripslashes() on array

I have some problems using stripslashes() on array.
Here is my array :
$tabRegion = array(
1=>"Alsace",
2=>"Aquitaine",
3=>"Auvergne",
4=>"Basse-Normandie",
5=>"Bourgogne",
6=>"Bretagne",
7=>"Centre",
8=>"Champagne-Ardenne",
9=>"Corse",
10=>"Franche-Comté",
(...)
21=>"Provence-Alpes-Côte d'Azur",
22=>"Rhône-Alpes",);
In order to stripslash, I have adapted this PHP code :
foreach ($tabRegion as $key=>$region) {
$tabRegion[$key] = stripslashes($region);
}
After in the file, I generate URL with it for example :
if (file_exists('../region/$tabRegion[$region]/$fonction/messages/$lecturefichier (...)
But the fact is that the last value of the array is always selected ("Rhône-Alpes") by the code... I don't know why.
Do you have an idea? :)
Thank you !
You are using foreach loop then you have to generate url in that loop.
In that loop you will get each region value
$tabRegion = array(
1=>"Alsace",
2=>"Aquitaine",
3=>"Auvergne",
4=>"Basse-Normandie",
5=>"Bourgogne",
6=>"Bretagne",
7=>"Centre",
8=>"Champagne-Ardenne",
9=>"Corse");
foreach ($tabRegion as $key=>$region)
{
$tabRegion[$key] = stripslashes($region);
print "<br>".$region;
}
Output will be :
Alsace
Aquitaine
Auvergne
Basse-Normandie
Bourgogne
Bretagne
Centre
Champagne-Ardenne
Corse
So that,you have to insert following line in that for loop :
if (file_exists('../region/$tabRegion[$region]/$fonction/messages/$lecturefichier (...)
You are using $region variable in foreach loop and you should know that it is treated like any other variable in your script. So for example:
$fruit = 'Banana';
foreach(array('Tomato', 'Orange') as $fruit) {
echo $fruit;
}
echo $fruit; // it will output 'Orange';

PHP foreach set row name as new variable

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();

Categories