0

I have the following code:

<?php
header ('Content-Type: text/html; charset=UTF-8'); 

$cars = array("Mike", "Paul", "Rita");

?>
    
<html>
<head>
<script>
function runFun(){
    var t = document.getElementById("t");
    let cID = t.selectedIndex;
    $c =  `<?php echo "I like " . $cars[cID]; ?>`;
    $c1 =  `<?php echo "I like " . $cars[1]; ?>`;
    window.alert($c);

 }
</script>
</head>
<body>
<select id="t" onchange="runFun();" name="t">
        <option value="<?php echo $cars[0] ?>"><?php echo $cars[0] ?></option>
        <option value="<?php echo $cars[1] ?>"><?php echo $cars[1] ?></option>
        <option value="<?php echo $cars[2] ?>"><?php echo $cars[2] ?></option>
        </select>
<p> 
</body>
</html>

I need to pass the selected index cID to php array index in the same page. Is it possible?

Thank you in advance.

Regards

I tried

<?php echo "I like " . $cars[. 'cID' .]; ?>

and

<?php echo "I like " . $cars[+${cID}+]; ?>`;

But non works for me

  • 1
    it is possible but you would need to use ajax to send an http request to the same page and use the callback to write to the page the thing you like. However to simply display a message, such as `"I like Rita"` based upon the `change` event then you do not need to send an ajax request at all - just some simple javascript – Professor Abronsius Jan 22 '23 at 11:02
  • 3
    You can't use JS variables in PHP like that. PHP and JS are not only two completely different languages, they also run in two completely different environments. You should read [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) to get an understanding on the order of things. While reading it, remember that PHP is server side and JS is client side. – M. Eriksson Jan 22 '23 at 11:04
  • _Side note:_ Since you already have the value you want in the option, you only need to do: `let $c = t.value;` to get the value of the selected item from the select. – M. Eriksson Jan 22 '23 at 11:10
  • Thank you @M.Eriksson for your valuable reply. It is clear now and I think I need the function to be run from PHP side of have the array from HTML side. Your second answer is right, however my orginal code consists of two dia array, thus I need the index of the selected option to print another value of the same array using the same index of the selected option. Thanks again – Java Script Jan 23 '23 at 07:58

0 Answers0