This post is one of my favourite posts on this site. Because I am gonna give you the solution that I personally went through. I was doing a project on Free Currency Converter PHP Script using Fixer io API. In that project, I was thinking of doing something creative like real time currency convert without using AJAX but the conversion result will be displayed on the same page without loading the page, again and again, each time I change the value to be calculated. I had to face the problem because I was using all the currency values in a combined PHP array. I just had to load the array in the browser so that we are able to get the result without hitting the JSON URL each time I need to change the value.
To overcome this problem I searched a lot but did not find the exact solution at that time.
So today in this post I am gonna show you
Suppose you have a PHP array like this one
$arraynew = array('codespeedy', 'coding solution site');
You can do the following :
<script> var array = <?php echo json_encode($arraynew); ?>; </script>
json_encode() function will encode the PHP array like a simple value, not an object and not an array.
Till this, it’s very much easy. But the main problem is that if you have a PHP array which is combined. That means the array which is having both key and value.
Combined array means the array which is holding both the values and their keys.
If you have two separate arrays in PHP then you can combine that using the below method:
$newarray = array_combine($array1, $array2);
array_combine() will combine the arrays.
Now the arrays are combined that means the new array will have a key as well as a value.
<script> var array=<?php print_r(json_encode($newarray)); ?>; </script>
you can check it with console log
it will print the value.
Hope you have enjoyed this tutorial. Comment in the below comment section if you have any doubt or question.