Reputation: 17
i am writing a php code that loops an array of variables using foreach and I am trying to get the name of variable to use it in the javascript code here's my code
$arr = array($devices1, $devices2, $devices3, $devices4, $devices5, $devices6);
foreach ($arr as $key => $value)
{
if($value == '1')
{
echo "
<script type=\"text/javascript\">
document.getElementById($key).checked = true;
</script>
";
}
}
when i run the code, $key takes values 0,1,2 what i need is to take devices1, devices2, devices3... so the names of the variables. Can anyone help me out?
Upvotes: 0
Views: 44
Reputation: 37711
Well, you can build the names your self ("devices" + ($key+1)) or make it an associative array (though it doesn't make much sense):
$arr = array('devices1'=>$devices1,'devices2'=>$devices2,'devices3'=>$devices3);// etc...
However, what makes the most sense is to use a simple string array:
$arr = array('devices1', 'devices2', 'devices3', 'devices4', 'devices5', 'devices6');
and then just use $value instead of $key in your JS snippet.
UPDATE
Here's how to use the associative array version:
FULL CODE
$arr = array('devices1'=>$devices1,'devices2'=>$devices2,'devices3'=>$devices3);
foreach ($arr as $key => $value)
{
if($value == '1') // $value will be the value of each array item
{
echo "
<script type=\"text/javascript\">
document.getElementById($key).checked = true; // and $key is the string key
</script> // like 'devices1', etc.
";
}
}
Upvotes: 2