221

How can I convert a PHP array in a format like this

Array
(
    [0] => 001-1234567
    [1] => 1234567
    [2] => 12345678
    [3] => 12345678
    [4] => 12345678
    [5] => AP1W3242
    [6] => AP7X1234
    [7] => AS1234
    [8] => MH9Z2324
    [9] => MX1234
    [10] => TN1A3242
    [11] => ZZ1234
)

to a Javascript array in the format below?

var cities = [
    "Aberdeen",
    "Ada",
    "Adamsville",
    "Addyston",
    "Adelphi",
    "Adena",
    "Adrian",
    "Akron",
    "Albany"
];
caiosm1005
  • 1,686
  • 1
  • 19
  • 31
user663878
  • 2,313
  • 2
  • 15
  • 7
  • 3
    Can you clarify your question? Are you really trying to create a JavaScript array, or are you trying to create a string you can put in a `script` tag that will create it, or are you trying to create [JSON](http://json.org) to send back in reply to an ajax request, or... (Also, worth checking out the **How to Format** box on the right-hand side when you're asking your question, and [the page linked](http://stackoverflow.com/editing-help) from the **[?]** just above the question area.) – T.J. Crowder Apr 11 '11 at 08:56

19 Answers19

494

I'm going to assume that the two arrays you've given for PHP and JS are not related, and they're just examples of how arrays look in the two languages. Clearly you're not going to be able to convert those sequences of letters and numbers into those city names.

PHP provides a function to convert PHP arrays into Javascript code: json_encode(). (technically, it's JSON format; JSON stands for JavaScript Object Notation)

Use it like this:

<script type='text/javascript'>
<?php
$php_array = array('abc','def','ghi');
$js_array = json_encode($php_array);
echo "var javascript_array = ". $js_array . ";\n";
?>
</script>

See also the manual page I linked above for more information.

Note that json_encode() is only available in PHP 5.2 and up, so if you're using an older version, you'll need to use an existing one -- the PHP manual page also includes comments with functions written by people who needed it. (but that said, if you're using anything older than PHP 5.2 you should upgrade ASAP)

Thomas Orlita
  • 1,554
  • 14
  • 28
Spudley
  • 166,037
  • 39
  • 233
  • 307
  • @Spudley Hi, I tried this, and in the javascript tried accessing the array created in php as such `console.log('stuff: ' + javascript_array[0]);`, but it says `javascript_array` has not been defined – user3871 Jan 16 '14 at 03:45
  • If your PHP array contains special characters, this will go wrong. You can escape special characters using urlencode() functions. See my answer: http://stackoverflow.com/questions/5618925/convert-php-array-to-javascript/24884659#24884659 – Ben Rogmans Jul 22 '14 at 10:19
  • @BenRogmans - PHP's `json_encode()` function does work with UTF-8 characters. If you're having an issue with it, then it's more likely that you've got other parts of your system in the wrong encoding that need to be changed - the output of `json_encode()` shouldn't need any additional encoding; that's kinda the whole point. – Spudley Jul 23 '14 at 06:28
  • Without doubt, the best approach to what OP wanted. I was wondering if JSON object really is same as an array... I mean consider a situation where I want to check if a value exists in my array and do `jsonEncodedObject.indexOf( 'my string' ) > -1`, it will most likely throw an error. For this to work, `jsonEncodedObject` should be an array of the form `['my string', 'a string', 'some string', 'other string' ]`. I tried it and the result was as I expected. – Fr0zenFyr Jun 01 '15 at 20:15
  • 1
    Just to point out that json_encode define a JavaScript object, *NOT* an array. – Patrick Moore Feb 15 '18 at 16:22
  • 1
    @PatrickMoore - if you're going to be pedantic about it, `json_encode` outputs a JSON string, which can represent either a JS object or a JS array, or even a single scalar value, if that's what you pass it. The examples in my answer will output a JavaScript array, not an object. – Spudley Feb 15 '18 at 22:53
  • Already upvoted this in 2018... I'd like to upvote again but can't – A. D'Alfonso May 27 '20 at 11:59
65

Spudley's answer is fine.

Security Notice: The following should not be necessary any longer for you

If you don't have PHP 5.2 you can use something like this:

function js_str($s)
{
    return '"' . addcslashes($s, "\0..\37\"\\") . '"';
}

function js_array($array)
{
    $temp = array_map('js_str', $array);
    return '[' . implode(',', $temp) . ']';
}

echo 'var cities = ', js_array($php_cities_array), ';';
Community
  • 1
  • 1
Udo G
  • 12,572
  • 13
  • 56
  • 89
  • 2
    agreed: if you're using and old PHP, you'll need to write your own. However, you should also consider upgrading your PHP if at all possible! – Spudley Apr 11 '11 at 09:25
  • 6
    Even if you're using old PHP, don't write your own, take an existing library that is maintained / used by more than one person/project. So this answer is only showing how something could be done, but it should not recommend this - regardless of the PHP version. E.g. http://pear.php.net/package/Services_JSON – hakre Feb 19 '13 at 09:32
  • You're right. However, the code above has been used/tested for years in two large projects. – Udo G Feb 19 '13 at 13:44
  • http://php.net/array_map - and `implode` uses values only so already ignoring keys. – hakre Feb 19 '13 at 14:41
  • Yes, that's intentional. Check the original question. – Udo G Feb 19 '13 at 19:31
  • 1
    BTW, *you* added the array_map call. And, honestly, there is no need to edit a perfectly valid answer to the original question and mark it with a "Security Notice" when it doesn't incur any security issues. – Udo G Feb 19 '13 at 19:39
  • 1
    @UdoG: if you disagree with an edit, you are free to edit it again yourself. hakre has a point that it would be sensible for someone reading this question to use a library that was *known* to be secure and well tested, eg from Pear rather than just taking this code on merit. Also, it's worth pointing out that PHP 5.2 was already out of support when this question was asked. As I write now, it has been unsupported for two years and has known security issues that will not be patched. It is therefore a security issue simply to be using PHP 5.2, before we even consider the code in this answer. – Spudley Feb 23 '13 at 20:11
  • is it insecure to simply swap over the values (i.e. `echo "jsArray.push(\"" . $result[$i]["column_name"] . "\");";`) ?????? – oldboy Apr 25 '18 at 18:46
44

Dumb and simple :

var js_array = [<?php echo '"'.implode('","', $php_array).'"' ?>];
Eric
  • 9,870
  • 14
  • 66
  • 102
  • 7
    **Just out of curiosity**: what would happen when string contains quote , double quotes and/or comma? – Nis Jun 30 '14 at 22:35
  • 1
    Since there is a function for this, that should be preferred over an improvised solution unless there is a good reason; no reason is herein stated. – cjbarth Jul 31 '14 at 15:49
  • works better for unicode characters (urdu in my case) – TheTechGuy Dec 04 '18 at 16:27
44

You do not have to call parseJSON since the output of json_encode is a javascript literal. Just assign it to a js variable.

<script type="text/javascript">
    //Assign php generated json to JavaScript variable
    var tempArray = <?php echo json_encode($php_array); ?>;

   //You will be able to access the properties as 
    alert(tempArray[0].Key);
</script>
Jaykishan
  • 1,409
  • 1
  • 15
  • 26
24

you can convert php arrays into javascript using php's json_encode function

<?php $phpArray = array(
          0 => 001-1234567, 
          1 => 1234567, 
          2 => 12345678, 
          3 => 12345678,
          4 => 12345678,
          5 => 'AP1W3242',
          6 => 'AP7X1234',
          7 => 'AS1234',
          8 => 'MH9Z2324', 
          9 => 'MX1234', 
          10 => 'TN1A3242',
          11 => 'ZZ1234'
    )
?>
<script type="text/javascript">

    var jArray= <?php echo json_encode($phpArray ); ?>;

    for(var i=0;i<12;i++){
        alert(jArray[i]);
    }

 </script>
kamal pal
  • 4,187
  • 5
  • 25
  • 40
Dipesh KC
  • 3,195
  • 3
  • 32
  • 50
  • 4
    that loop is terrible – Eric Sep 03 '15 at 13:02
  • 2
    Well that was for demonstration purpose :) – Dipesh KC Sep 03 '15 at 15:45
  • 7
    @Eric the example was directly taken __as it is__ from the question. I could have used ```console.log()``` but the question itself is very basic (and user many not have experience with the browser code inspect tool ), so I decided to go with alert() since the user will see it directly.But you know it very well it is not the concerned part of the question, just a way to verify if the logic works or not. – Dipesh KC Sep 04 '15 at 08:41
18

I find the quickest and easiest way to work with a PHP array in Javascript is to do this:

PHP:

$php_arr = array('a','b','c','d');

Javascript:

//this gives me a JSON object
js_arr = '<?php echo JSON_encode($php_arr);?>';


//Depending on what I use it for I sometimes parse the json so I can work with a straight forward array:
js_arr = JSON.parse('<?php echo JSON_encode($php_arr);?>');
user3065931
  • 531
  • 7
  • 20
18

Is very simple I use this way:

JAVASCRIPT:

var arrayJavascript = <?php echo json_encode($arrayPhp) ?>;

Convert PHP array to Javascript

Regards!

Radames E. Hernandez
  • 4,235
  • 27
  • 37
15

u can also do in this way

<script>  
    <?php 
        $php_array = array('abc','def','ghi');
    ?>  
    var array_code = <?php echo json_encode($php_array); ?>;
    console.log(array_code);
</script>
Rabby
  • 322
  • 4
  • 15
cool Quazi
  • 218
  • 2
  • 8
14

so simple ...!

use this method:

<?php echo json_encode($your_array); ?>; 

in laravel blade {{ }} use this method:

{{ str_replace('&quot;', '', json_encode($your_array)) }} 

working for associated and unassociated array.

3

This is my function. JavaScript must be under PHP otherwise use SESSION.

<?php
 $phpArray=array(1,2,3,4,5,6);
?>

<div id="arrayCon" style="width:300px;"></div>

<script type="text/javascript">
var jsArray = new Array();
<?php
 $numArray=count($phpArray);
 for($i=0;$i<$numArray;$i++){
  echo "jsArray[$i] = ". $phpArray[$i] . ";\n";
 }
?>
$("#arrayCon").text(jsArray[1]);
</script>

Last row can be ....text(jsArray); and will be shown "1,2,3,4,5,6"

CJ Ramki
  • 2,620
  • 3
  • 25
  • 47
japetko
  • 354
  • 4
  • 14
2

For a multidimensional array in PHP4 you can use the following addition to the code posted by Udo G:

function js_str($s) {
   return '"'.addcslashes($s, "\0..\37\"\\").'"';
}

function js_array($array, $keys_array) {
  foreach ($array as $key => $value) {
    $new_keys_array = $keys_array;
    $new_keys_array[] = $key;
    if(is_array($value)) {          
      echo 'javascript_array';
      foreach($new_keys_array as $key) {
        echo '["'.$key.'"]';
      }
      echo ' = new Array();';

      js_array($value, $new_keys_array);
    } else {
      echo 'javascript_array';
      foreach($new_keys_array as $key) {
        echo '["'.$key.'"]';
      }
      echo ' = '.js_str($value).";";                        
    }
  } 
}

echo 'var javascript_array = new Array();';
js_array($php_array, array());
Sander
  • 339
  • 1
  • 3
  • 11
2

I use a fake php array

<?php 
       // instead to create your array like this
       $php_array = ["The","quick","brown","fox","jumps","over","the","lazy","dog"];

       // do it like this (a simple variable but with separator)
       $php_fake_array = "The,quick,brown,fox,jumps,over,the,lazy,dog";
?>

<script type="text/javascript">

        // use the same separator for the JS split() function
        js_array = '<?php echo $php_fake_array; ?>'.split(',');

</script>

if ever your array is unknown (already made)

<?php 
        $php_array = file('my_file.txt');
        $php_fake_array = "";

        // transform your array with concatenate like this
        foreach ($php_array as $cell){

            // since this array is unknown, use clever separator
            $php_fake_array .= $cell.",,,,,"; 
        }
?>

<script type="text/javascript">

        // use the same separator for the JS split() function
        js_array = '<?php echo $php_fake_array; ?>'.split(',,,,,');

</script>
Mik
  • 29
  • 1
  • ...or you could implode() the first array to get the "fake" one. I know this is an old response, but the idea just crossed my mind. – Peter Mghendi Jan 26 '20 at 20:47
  • 1
    sure, but my way is the fastest of all suggestions on this page. Sometimes, speed could be an important factor. – Mik Jan 31 '20 at 01:21
0

I had the same problem and this is how i done it.

/*PHP FILE*/

<?php

$data = file_get_contents('http://yourrssdomain.com/rss');
$data = simplexml_load_string($data);

$articles = array();

foreach($data->channel->item as $item){

    $articles[] = array(

        'title' => (string)$item->title,
        'description' => (string)$item ->description,
        'link' => (string)$item ->link, 
        'guid' => (string)$item ->guid,
        'pubdate' => (string)$item ->pubDate,
        'category' => (string)$item ->category,

    );  
}

// IF YOU PRINT_R THE ARTICLES ARRAY YOU WILL GET THE SAME KIND OF ARRAY THAT YOU ARE GETTING SO I CREATE AN OUTPUT STING AND WITH A FOR LOOP I ADD SOME CHARACTERS TO SPLIT LATER WITH JAVASCRIPT

$output="";

for($i = 0; $i < sizeof($articles); $i++){

    //# Items
    //| Attributes 

    if($i != 0) $output.="#"; /// IF NOT THE FIRST

// IF NOT THE FIRST ITEM ADD '#' TO SEPARATE EACH ITEM AND THEN '|' TO SEPARATE EACH ATTRIBUTE OF THE ITEM 

    $output.=$articles[$i]['title']."|";
    $output.=$articles[$i]['description']."|";
    $output.=$articles[$i]['link']."|";
    $output.=$articles[$i]['guid']."|";
    $output.=$articles[$i]['pubdate']."|";
    $output.=$articles[$i]['category'];
}

echo $output;

?>
/* php file */


/*AJAX COMUNICATION*/

$(document).ready(function(e) {

/*AJAX COMUNICATION*/

var prodlist= [];
var attrlist= [];

  $.ajax({  
      type: "get",  
      url: "php/fromupnorthrss.php",  
      data: {feeding: "feedstest"},
      }).done(function(data) {

        prodlist= data.split('#');

        for(var i = 0; i < prodlist.length; i++){

            attrlist= prodlist[i].split('|');

            alert(attrlist[0]); /// NOW I CAN REACH EACH ELEMENT HOW I WANT TO. 
        }
   });
});

I hope it helps.

Matt
  • 3,079
  • 4
  • 30
  • 36
0

Keep it simple :

var jsObject = JSON.parse('<?= addslashes(json_encode($phpArray)) ?>');
Fifi
  • 3,360
  • 2
  • 27
  • 53
0

for php use this :

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

for blade use this:

var js_array = {{ Js::from($php_array) }};

or simply use this:

var js_array @json($php_array)

docs : https://laravel.com/docs/10.x/blade#rendering-json

fartoot
  • 15
  • 4
-1

If you need a multidimensional PHP array to be printed directly into the html page source code, and in an indented human-readable Javascript Object Notation (aka JSON) fashion, use this nice function I found in http://php.net/manual/en/function.json-encode.php#102091 coded by somebody nicknamed "bohwaz".

<?php

function json_readable_encode($in, $indent = 0, $from_array = false)
{
    $_myself = __FUNCTION__;
    $_escape = function ($str)
    {
        return preg_replace("!([\b\t\n\r\f\"\\'])!", "\\\\\\1", $str);
    };

    $out = '';

    foreach ($in as $key=>$value)
    {
        $out .= str_repeat("\t", $indent + 1);
        $out .= "\"".$_escape((string)$key)."\": ";

        if (is_object($value) || is_array($value))
        {
            $out .= "\n";
            $out .= $_myself($value, $indent + 1);
        }
        elseif (is_bool($value))
        {
            $out .= $value ? 'true' : 'false';
        }
        elseif (is_null($value))
        {
            $out .= 'null';
        }
        elseif (is_string($value))
        {
            $out .= "\"" . $_escape($value) ."\"";
        }
        else
        {
            $out .= $value;
        }

        $out .= ",\n";
    }

    if (!empty($out))
    {
        $out = substr($out, 0, -2);
    }

    $out = str_repeat("\t", $indent) . "{\n" . $out;
    $out .= "\n" . str_repeat("\t", $indent) . "}";

    return $out;
}

?>       
Heitor
  • 683
  • 2
  • 12
  • 26
  • Please nevermind!! Now we can just use this: json_encode($array, JSON_PRETTY_PRINT); and be happy! – Heitor Mar 18 '17 at 09:27
-1

Below is a pretty simple trick to convert PHP array to JavaScript array:

$array = array("one","two","three");

JS below:

// Use PHP tags for json_encode()

var js_json =  json_encode($array);
var js_json_string = JSON.stringify(js_json);
var js_json_array = JSON.parse(js_json_string);

alert(js_json_array.length);

It works like a charm.

Badacadabra
  • 8,043
  • 7
  • 28
  • 49
-1

Many good and complex solutions are here and this is a way to doing it without parsing json in user side.

$mtc=array();
$replace=array();

$x = json_encode($thearray);

preg_match_all('/"[a-z0-9_]*":/',$x,$mtc);

foreach($mtc[0] as $v){
    array_push($replace,str_replace('"','',$v));
}
    
$x = str_replace($mtc[0],$replace,$x);

echo '<script type="text/javascript">x='.$x.';console.log(x);</script>';

This works with both indexed and associative arrays(any combination) which has multiple levels, and no need for user side json parsing.

Aylian Craspa
  • 422
  • 5
  • 11
-1

For Laravel user: use @json

var cities = @json($data);

As explained in official docs: https://laravel.com/docs/8.x/blade#rendering-json:

hungtran273
  • 1,180
  • 9
  • 11