-1

I have a php array "$values", i want to transfer its values to a js array, which is working well, the only problem i'm getting is that it's making the 2 values sended stuck together as "onetwo" while i want them to be as two different values ["one","two"] in my Js array.

<?php 
  $values= ["one", "two"];
?>

<script>
var Js_array = [];

    Js_array.push('<?php 

        for ($x = 0; $x < count($values); $x++) {
            echo $values[$x];
        } 
    ?>'); 

alert(Js_array);
</script>

Thanks for your help.

alioua walid
  • 247
  • 3
  • 19

2 Answers2

1

You are currently echoing all the items of the php array into ONE instance of the Js_array.push() function, so Js_array.push adds all the items of your php array as 1 item into the javascript array.

You instead should invoke Js_array.push() on each item of the php array, so each item can be added to the javascript array seperately. The below code demonstrates the required modification:

<?php 
  $values = ["one", "two"];
?>

<script>
  var Js_array = [];

  <?php 

    for ($x = 0; $x < count($values); $x++) {
        echo 'Js_array.push("'.$values[$x].'");'; // call Js_array.push on each item of php array;
    } 
  ?>;

  alert(Js_array);
</script>
coderodour
  • 1,072
  • 8
  • 16
0
<?php 
  $values= ["one", "two"];
  function addQuotes($each_value){
     return "'".$each_value."'";
  }
?>

<script>
var Js_array = [<?php echo implode(",",array_map("addQuotes",$values)); ?>];
alert(Js_array);
</script>
nice_dev
  • 17,053
  • 2
  • 21
  • 35