You can use json_encode() to make array as an json object like,

var words = <?php echo json_encode($wordsArray) ?>;// don't use quotes
$.each(words, function(key, value) {
    console.log('stuff : ' + key + ", " + value);
});
Answer from Rohan Kumar on Stack Overflow
Discussions

Converting a php object to javascript array - Stack Overflow
In my php file, I have added the above autofill function after the form. Then I use json_encode on this object followed by JSON.parse. I use a loop to add just the names to a javascript array, and finally I pass it to the autocomplete function. More on stackoverflow.com
๐ŸŒ stackoverflow.com
May 15, 2018
How to convert a JavaScript object to a PHP array and get the raw string? - Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... In my application I need to convert a JavaScript Object to a raw PHP array returned as text string. I would do this calling an API. I don't need to manupulate the array. More on stackoverflow.com
๐ŸŒ stackoverflow.com
passing PHP objects to javascript - Stack Overflow
Ideally, mirroring the same structure, so I can use Raphael to display each item and its info as separate shapes on my site. However, how do you get an object from php to javascript? ... You can convert the PHP object to an array, and then use JSON function to encode it. More on stackoverflow.com
๐ŸŒ stackoverflow.com
PHP array() to javascript array() - Stack Overflow
Notice that PHP's associative array becomes an object literal in JavaScript. We use the JSON_PRETTY_PRINT option as the second argument to json_encode to display the output in a readable format. You can access object properties using dot syntax, as displayed with the alert included above, or square bracket syntax: book['title']. ... When we convert ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ How-to-convert-PHP-array-to-JavaScript-array
How to convert PHP array to JavaScript array?
June 18, 2020 - You can use PHP array in JavaScript. It works for the single as well as the multidimensional array. Use the json_encode() method to achieve this. ... Converting PHP array into JavaScript.
๐ŸŒ
CodexWorld
codexworld.com โ€บ home โ€บ how to guides โ€บ how to convert php array to javascript array
How to Convert PHP Array to JavaScript Array - CodexWorld
February 26, 2025 - Convert PHP Array to JavaScript Array - Use json_encode() function to convert PHP indexed, associative, and multidimensional array to JavaScript array. The example code to convert PHP array and access in JavaScript.
๐ŸŒ
DEV Community
dev.to โ€บ ankitvermaonline โ€บ convert-php-array-to-javascript-2050
Convert php array to Javascript - DEV Community
May 27, 2025 - <script type="text/javascript"> // Assign PHP user array to a JS variable var user = <?php echo json_encode($user); ?>; console.log(user); </script> Output in JavaScript: { name: "John Doe", email: "john@example.com", is_admin: true, age: 30 } Subscribe ยท For further actions, you may consider blocking this person and/or reporting abuse ยท
๐ŸŒ
Wtools
wtools.io โ€บ convert-php-array-to-js-object
Convert PHP array to Javascript object Online - wtools.io
{ first_section: { one: "1", test: "sample", animal: "BIRD" }, second_section: { path: "/var/test", URL: "https://wtools.io/", second_section: { 0: "1 unassociated", 1: "2 unassociated", one: "1 associated", two: "2 associated" } }, third_section: { version: [ "7.0", "7.1", "7.2", "7.3" ] } } After the conversion, you can apply the JS object to your project or use it for some other purpose. ... Did you like this tool? You can donate to us. This will help us improve our free web tools. Paypal ... Convert JS Object to PHP arrayConvert PHP Array to JSONConvert PHP Array to XMLConvert PHP Array to YAMLSerialize PHP array
Find elsewhere
๐ŸŒ
Jonathan Suh
jonsuh.com โ€บ blog โ€บ convert-loop-through-json-php-javascript-arrays-objects
Convert and Loop through JSON with PHP and JavaScript Arrays/Objects โ€” Jonathan Suh
September 30, 2014 - <?php // Array $someArray = [ [ "name" => "Jonathan Suh", "gender" => "male" ], [ "name" => "William Philbin", "gender" => "male" ], [ "name" => "Allison McKinnery", "gender" => "female" ] ]; // Convert Array to JSON String $someJSON = json_encode($someArray); echo $someJSON; ?> Note that Iโ€™m using the short array syntax thatโ€™s featured in PHP 5.4+. <?php $array = array( "foo" => "bar", "bar" => "foo" ); // as of PHP 5.4 $array = [ "foo" => "bar", "bar" => "foo" ]; ?> JavaScript has a built-in JSON.parse() method that parses a JSON string and returns an object.
๐ŸŒ
W3docs
w3docs.com โ€บ home โ€บ code snippets โ€บ php โ€บ how to convert a php array to a javascript array
How to Convert a PHP Array to a JavaScript Array | W3docs
To convert a PHP array to a JavaScript array, you should pass it and then apply <kbd class="highlighted">json_encode</kbd>. ... <script type='text/javascript'> <?php $php_array = [['W3docs', '[email protected]'], ['for', '[email protected]']]; ...
๐ŸŒ
sebhastian
sebhastian.com โ€บ php-array-to-javascript-array
Convert PHP array to JavaScript array (with code examples) | sebhastian
September 19, 2022 - A PHP array can be converted into a JavaScript array by using the json_encode() function.
๐ŸŒ
YouTube
youtube.com โ€บ watch
How to convert a php array to javascript array - YouTube
In this video we'll discuss that how to pass or convert a php array to javascript.
Published: July 25, 2020
Top answer
1 of 9
47

To convert you PHP array to JS , you can do it like this :

var js_array = [<?php echo '"'.implode('","',  $disabledDaysRange ).'"' ?>];

or using JSON_ENCODE :

var js_array =<?php echo json_encode($disabledDaysRange );?>;

Example without JSON_ENCODE:

<script type='text/javascript'>
    <?php
    $php_array = array('abc','def','ghi');
    ?>
    var js_array = [<?php echo '"'.implode('","', $php_array).'"' ?>];
    alert(js_array[0]);
</script>

Example with JSON_ENCODE :

<script type='text/javascript'>
    <?php
    $php_array = array('abc','def','ghi');
    ?>
    var js_array =<?php echo json_encode($disabledDaysRange );?>;
    alert(js_array[0]);
</script>
2 of 9
18

The PHP json_encode function translates the data passed to it to a JSON string which can then be output to a JavaScript variable.The PHP json_encode function returns a string containing the JSON equivalent of the value passed to it.

<?php
$ar = array('apple', 'orange', 'banana', 'strawberry');
echo json_encode($ar); // ["apple","orange","banana","strawberry"]
?>

You can pass the JSON string output by json_encode to a JavaScript variable as follows:

<script type="text/javascript">
// pass PHP variable declared above to JavaScript variable
var ar = <?php echo json_encode($ar) ?>;
</script>

A numerically indexed PHP array is translated to an array literal in the JSON string. A JSON_FORCE_OBJECT option can be used if you want the array to be output as an object instead:

<?php
echo json_encode($ar, JSON_FORCE_OBJECT);
// {"0":"apple","1":"orange","2":"banana","3":"strawberry"} 
?>

Associative Array Example:

<?php
$book = array(
    "title" => "JavaScript: The Definitive Guide",
    "author" => "David Flanagan",
    "edition" => 6
);
?>
<script type="text/javascript">
var book = <?php echo json_encode($book, JSON_PRETTY_PRINT) ?>;
/* var book = {
    "title": "JavaScript: The Definitive Guide",
    "author": "David Flanagan",
    "edition": 6
}; */
alert(book.title);
</script>

Notice that PHP's associative array becomes an object literal in JavaScript. We use the JSON_PRETTY_PRINT option as the second argument to json_encode to display the output in a readable format.

You can access object properties using dot syntax, as displayed with the alert included above, or square bracket syntax: book['title'].

here you can find more information and details.

๐ŸŒ
Reddit
reddit.com โ€บ r/learnjavascript โ€บ how javascript to convert a php array into a javascript array
r/learnjavascript on Reddit: How JavaScript to convert a PHP array into a JavaScript array
August 13, 2021 -

I found this cool snippet of code that will create a table in JavaScript. I like it because it will allow multiple columns. The onLoad shows how to create the table correctly as I found it.

  1. in function havePHPcreateTable()
    How do I iterate through the array and remove the quotes on the keys (name:, color:, price:) that was formatted by PHP?

  2. also in function havePHPcreateTable()
    The createTable([]) creates a different type of object than the PHP array, how do I get PHP or reformat it into the correct type of object ?

TestTable.js:

var TBL_NAME = 'tblDIV';

bIsLoaded = false;

cPrev = -1;

window.onload=onLoad;

function onLoad()
{
    bIsLoaded = true;

    createTable([
        {name: 'Banana', price: '3.04', color:'yellow'},
        {name: 'Orange', price: '2.56', color:'orange'},
        {color:'red', name: 'Apple', price: '1.45'},
        {name: 'Cantaloupe', price: '2.45', color:'peach'},
        {price: '5.12', name:'Dates', color:'black'}
        ],
        ['name', 'price', 'color'], ['Name', 'Price', 'Color']);

    havePHPcreateTable();
}

function createTable(objectArray, fields, fieldTitles) 
{
    if (!bIsLoaded)
        return;

    let body_table = document.getElementById(TBL_NAME);
    let tbl = document.createElement('table');
    let thead = document.createElement('thead');
    let thr = document.createElement('tr');

    var i = 0;
    fieldTitles.forEach((fieldTitle) => {
      let th = document.createElement('th');
      th.appendChild(document.createTextNode(fieldTitle));
      const abc = i; //  needs const otherwise all i's will be the same
      th.onclick=(function(){ sortTable(abc); });
      thr.appendChild(th);
      i++;
    });

    thead.appendChild(thr);
    tbl.appendChild(thead);
  
    let tbdy = document.createElement('tbody');
    let tr = document.createElement('tr');
    objectArray.forEach((object) => {
      let tr = document.createElement('tr');
      fields.forEach((field) => {
        var td = document.createElement('td');
        td.appendChild(document.createTextNode(object[field]));
        td.onclick=(function(){ alert('click '); });
        tr.appendChild(td);
      });
      tbdy.appendChild(tr);    
    });
    tbl.appendChild(tbdy);
    body_table.appendChild(tbl)
    return tbl;
}

function havePHPcreateTable()
{
    var myList = getPHP();
    var myListA = myList[0].shift();
    var myListB = myList[0].shift();

    createTable(myListA, myListB, myListB);

}

function getPHP()
{
    myObjB = null;
    $.get({
        async: false,  // need to add a wait for reply statement
	url: 'TestTable.php',
	success: function(result)
	{
	    if (result !== 'null' && result.length > 1)
    	    {
                myObjB = JSON.parse(result);
            }
        }
    });
    return myObjB;
}

TestTable.php

<?php

function getTable()
{
    $name = "apple";
    $price = "1.03";
    $color = "red";

    $abc_item[] = array(
        'name:' => $name,
        'price:' => $price,
        'color:' => $color
      );
    
    $abc_list[] = array('name', 'price', 'color');
    
    $abc[] = array($abc_item, $abc_list);

    return $abc;
}

echo json_encode(getTable());

?>
Top answer
1 of 1
2
[ [ [ [ "name:" => "apple", "price:" => "1.03", "color:" => "red" ] ], [ [ "name", "price", "color" ] ] ] ] is what the PHP file returns. Needless to say that's a lot of unnecessary nesting. All you need is an array of associative arrays for each row: function getTable() { return [ [ "name:" => "apple", "price:" => "1.03", "color" => "red" ], [ "name:" => "orange", "price:" => "1.15", "color:" => "orange" ], ]; } echo json_encode(getTable()); Then you can fetch the encoded table from a JS file: fetch("./TestTable.php") .then(res => res.text()) .then(data => { const table = convertJSONArrayToHTMLTable(data); // Insert table into document document.body.append(table); }); function convertJSONArrayToHTMLTable(jsonArray) { jsonArray = JSON.parse(jsonArray); const table = document.createElement("table"); // Create table head const headers = Object.keys(jsonArray[0]); const thead = document.createElement("thead"); const thead_tr = document.createElement("tr"); headers.forEach(header => { // Remove colon header = header.replace(":", ""); const th = document.createElement("th"); th.textContent = header; thead_tr.append(th); }); thead.append(thead_tr); // Create tbody const tbody = document.createElement("tbody"); // Create row for each object jsonArray.forEach(object => { const row = document.createElement("tr"); // Create cell for each value Object.values(object).forEach(value => { const cell = document.createElement("td"); cell.textContent = value; row.append(cell); }); tbody.append(row); }); table.append(thead, tbody); return table; }
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 34394638 โ€บ converting-php-array-to-javascript-object
Converting PHP array to JavaScript Object - Stack Overflow
and I am storing the SQL data on a php array directly after retrieving the row. Now, using JSON approach, here was my trial but apparently it isn't loading or working. var mapObject, markers = [], markersData = JSON.parse( '<?php echo json_encode($markersData); ?>' ); And I'm looking for the converted php array to do the same job as this JS code:
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 49269963 โ€บ how-to-convert-php-array-to-javascript-array-in-php
How to convert php array to javascript array in php - Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Save this question. Show activity on this post. I'm working on core php,i need how to convert PHP array to Javascript array please help me,below the my example code this there please check it.
๐ŸŒ
Source Code Tester
sourcecodester.com โ€บ tutorial โ€บ php โ€บ 15704 โ€บ converting-php-array-javascript-array-tutorial
Converting PHP Array into JavaScript Array Tutorial | SourceCodester
September 29, 2022 - The following snippets are an example of converting an array of data from PHP to JS using the said method. ... The other way to convert an Array of data from PHP to JS is by using For Loop. Using this, you can store the object data into an array ...