Back to Top

How to convert PHP array to JavaScript array?

To convert PHP array into Javascript array

Sometimes you want to get PHP array values into JavaScript as an array. Mostly when you are using ajax. In Ajax, we pass PHP data into ajax request and multiple data generate as response which is in array But array format of PHP and JavaScript are different.

So, Today I am going to explain how you pass PHP data and convert into a JavaScript array.

So, Let’s understand code:

//PHP
$new_arr = array();
foreach($exist_array as $key =>$value)
{
	$new_arr.='"'.$key.'":"'.$value.'",';
}
$new_arr=substr($exist_array,0,-1);

echo $new_arr="{".$new_arr."}";

Here, I have used foreach loop and convert into JavaScript json encode format.

Read: JavaScript Ticker for Database Values

//Javascript

var result_set=$.parseJSON(response);
var result_array=[];
for(i in result_set){
	result_array.push(result_set[i]);
}

Here, I have decoded JSON encoded values return in ajax response and generate the JavaScript array.

Read about: Convert 12-hour datetime to 24-hour datetime in JavaScript

you can check using $.isArray() function,see

console.log($.isArray(result_array));

we’re done.I hope that you like this trick.I’m hoping that you’ve found this tutorial useful.

Don’t hesitate to use this code and post your comments if you need help. As always, thanks for reading. Don’t Forget to Follow us on Twitter or Subscribe us to Get the Latest Updates.

Comments (4)

  1. there is error at line no 2
    $new_arr = array();
    it should be
    $new_arr = “”;
    AND Hence
    $new_arr=substr($exist_array,0,-1);
    should be
    $new_arr=substr($new_arr,0,-1);

    1. Yeah my mistake, thanks for your comment

  2. Why wouldn’t use just use PHP’s json_encode method?

    $json = json_encode($exist_array);

    Done.

    1. As we are coverting PHP array javascript, json_encode is for PHP only

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Most Popular Posts

How to convert Object to array in PHP

Posted on 2 years ago

Bhumi

What is Press This in WordPress

Posted on 7 years ago

Bhumi

How To set up Signup Bonus in X-Cart

Posted on 6 years ago

Bhumi

The Reader’s Poll – June 2015

Posted on 3 years ago

Bhumi

The Reader’s Poll – August 2014

Posted on 4 years ago

Bhumi

The Reader’s Poll – June 2014

Posted on 5 years ago

Bhumi

The Readers’ Poll – May 2014

Posted on 5 years ago

Bhumi

The Readers’ Poll – August 2013

Posted on 5 years ago

Bhumi