Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
get php variable by a javascript variable

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!