0

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?

4
  • When i see devices4 .... n times there is already a chance that this could be written better Commented Sep 11, 2014 at 20:34
  • 1
    Sidenote: checked == true; should most likely be checked = true; Commented Sep 11, 2014 at 20:35
  • thats for the sake of the question, i just need to know how can i tell php to take the variable name not the values or indexes @true Commented Sep 11, 2014 at 20:35
  • 1
    sorry @Fred-ii- i edited it Commented Sep 11, 2014 at 20:37

1 Answer 1

2

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.
";
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

but if i do this, i will loose the values stored in it no?
You're not doing anything with the values.
I wasn't sure if you needed the values - if you do, go with the associative array.
i need the values in the if condition, i was trying to say that if devices1 contains 1 for example, i need to check its checkbox
Got it, I thought they were just being 0,1,2, etc. Use associative array and you'll be able to use both the keys and the values.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.