0

Want javascript variable as index variable in php array in javascript.

Code is not working .....

<script>
     var total = <?php echo count($resvalue); ?> ; //$resvalue is an array holding the values are 1,2,3,4. total will hold count of that array.
     for(var j=0;j<total;j++)
     {
          <php echo $resvalue[j]; ?> // where j is javascript variable and $resvalue is PHP array
     }
 </script>
8
  • 3
    JavaScript is executed on the client side, PHP on the server side. You can't mix and match. Commented Aug 9, 2017 at 6:17
  • then what will be the solution for this ? Commented Aug 9, 2017 at 6:18
  • You can solve your problem by either sending the $resvalue to the client using API call, or by using full php code Commented Aug 9, 2017 at 6:19
  • Don't know your use case. For the simple code you're showing, you can easily just do everything in PHP. Commented Aug 9, 2017 at 6:19
  • can you clarify your question. also, you have an error in your code... <php echo... should be <?php echo... you also have another error in your for loop. it should be total.length and not total... Commented Aug 9, 2017 at 6:20

1 Answer 1

2

You cannot read values in a php array from javascript. Instead echo the array and turn it into a javascript array and let javascript do the count.

<script>
     var resvalue = [<?php echo $resvalue; ?>]; // or something like this
     for(var j=0; j < resvalue.length; j++)
     {
          // your value is available in the js-array
          // resvalue[j]
     }
</script>

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.