I am creating variables from loops in PHP and JavaScript using the same names. These names are stored in arrays (one in PHP and the other one in JS). Each variable in PHP has information that I need to pass in JavaScript. Now, this is working:
vars_jsarray =["Name1", "Name2", "Name3"];
for (var i = 0; i < vars_jsarray.length; i++){
this[vars_jsarray[i]] = [<?=${$vars_phparray[0]};?>];
}
I want to change that "0" and use variable "i" instead. Something like this could work too (because the arrays are the same):
vars_jsarray =["Name1", "Name2", "Name3"];
for (var i = 0; i < vars_jsarray.length; i++){
this[vars_jsarray[i]] = [<?=${vars_jsarray[i]};?>];
}
How could I access to PHP variable using this JavaScript loop?
Assuming the arrays are exactly the same, drop the JS loop and use a PHP one:
<?php
for ($i = 0; $i < count($vars_phparray); $i++){
echo "this[ {$vars_phparray[$i]} ] = [ {$vars_phparray[$i]} ];";
}
?>
Although in future you may find that this way of working gets very messy, very quickly.
Instead you could use some AJAX to grab data from your server as it described here.
Off the top of my head
vars_jsarray =["Name1", "Name2", "Name3"];
vars_js_phparray = [<?=implode("," $vars_phparray);?>]
for (var i = 0; i < vars_jsarray.length; i++){
this[vars_jsarray[i]] = [vars_js_phparray[i]];
}
Not sure if that solves your requirement but based on your example it is an exact replica.
You are misunderstanding how PHP works; this is most certainly not going to work - not in its current form.
In general, PHP will first produce a HTML document which is then sent to the client (browser). At this point the PHP script is finished with executing your server side code*.
The produced document can of course contain JavaScript, which will run on the client after the actual page has been sent to the client. There is no back-and-forth communication, not unless you use AJAX calls, but that is much more well structured than plain language-mixing.
That is, in this case you basically write JavaScript to the client's browser using PHP, which will be ran on the client. Consider the following example:
PHP code
echo "<script>";
for ($i = 0; $i < 3; $i++)
{
echo "console.log('Let us write something into console: $i');";
}
echo "</script>";
This code will send the following page to the client:
HTML/JavaScript
<script>
console.log('Let us write something into console: 0');
console.log('Let us write something into console: 1');
console.log('Let us write something into console: 2');
</script>
When the above very simple Javascript is executed, there is no way of accessing PHP's $i
variable that was used to create it, since it no longer exists. Certainly not on the client's machine.
*assuming an output buffer is used, otherwise the page is sent as it is created, line-by-line.
You can access PHP variables within JS accordingly:
var jsVar = <?php echo $phpVar; ?>;
But, again, I don't recommend it. Use AJAX.