-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.

2

2 Answers 2

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

2 Comments

Thanks for your answer, and the explanation as well :)
Glad to help, thanks for quick response. Best of luck.
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>

1 Comment

Code only answers are discouraged. You should explain what you did and why you did it. Otherwise answers will be deleted.

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.