0

I've got 4 PHP variables, and I have 1 Javascript variable with the name of one of those 4 PHP variables, how can reference it?

$p1 = ...
$p2 = ...
$p3 = ...
$p4 = ...

<script>
    var myoption = 'p1';
    var myarray = <?= $p1 ?>;
    console.log(myarray);
</script>

In this case instead of setting myarray to $p1, I want to do it with myoption, once myoption can be p2 or p3

5
  • 2
    If myoption is going to be set dynamically in js then you'll have to use something like ajax to get the value of the variable you want. Commented Jan 8, 2022 at 16:23
  • got it, and for example can I set the js variable to a php function return? Commented Jan 8, 2022 at 16:24
  • 2
    You need to understand what runs at what point, first PHP is run / executed / interpreted, then the result of the php file is returned to the client where the JavaScript may be executed. Commented Jan 8, 2022 at 16:32
  • yes, in this case the php variable is already set, I just need what is there, has the same order that above Commented Jan 8, 2022 at 16:42
  • When, where, and how does myoption vary? Please edit your question to show more specifics. Commented Jan 8, 2022 at 18:26

1 Answer 1

1

You can create a PHP array, json_encode it into your Javascript, like this:

$p1 = ...
$p2 = ...
$p3 = ...
$p4 = ...

$myPHPArray = [
    'p1' => $p1,
    'p2' => $p2,
    'p3' => $p3,
    'p4' => $p4
];

<script>
    var myoption = 'p1';
    var myarray = <?php echo json_encode($myPHPArray) ?>;
    console.log(myarray[myoption]);
</script>
Sign up to request clarification or add additional context in comments.

Comments

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.