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:

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

Read: JavaScript Ticker for Database Values

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

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

The Reader’s Poll – August 2014

Posted on 10 years ago

Bhumi