How to convert PHP array to JavaScript Array

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

  1. How to convert PHP array to JavaScript array
  2. How to convert combined PHP array to JavaScript array

You can also say How to store the PHP array variable to JavaScript array variable

So at first, see the basic of storing PHP array to JavaScript array

How to convert JSON string to PHP Array?

Remove duplicate values from an array in PHP

Convert PHP Array To JavaScript Array

Suppose you have a PHP array like this one

$arraynew = array('codespeedy', 'coding solution site');

Now you have to store PHP array to JavaScript array

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.

How to get the array key for a given value in PHP?

How to convert JSON string to PHP Array?

Convert combined PHP array To JavaScript array

Now we gonna learn how to store combined PHP array into JavaScript array variable.

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.

Now you have to convert combine array to JavaScript array.

<script>
var array=<?php print_r(json_encode($newarray)); ?>;
</script>

you can check it with console log

console.log(array[key]);

it will print the value.

Merge Multiple Arrays Into one Array Using PHP array_merge() Function

Hope you have enjoyed this tutorial. Comment in the below comment section if you have any doubt or question.

Leave a Reply

Your email address will not be published. Required fields are marked *