Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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"
];
share|improve this question
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 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 from the [?] just above the question area.) –  T.J. Crowder Apr 11 '11 at 8:56
3  
How do you turn these numbers into those names? I'm pretty sure they're not standard country codes. Besides, indices 2, 3, and 4 are the same but resolve to different countries? –  bdares Apr 11 '11 at 8:56

10 Answers 10

up vote 18 down vote accepted

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), ';';
share|improve this answer
    
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 9:25
5  
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. pear.php.net/package/Services_JSON –  hakre Feb 19 '13 at 9: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
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

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; PHP is currently at v5.3, and even 5.2 is no longer supported)

share|improve this answer
    
You're missing a semicolon at the end of the javascript array, and also that's not the way PHP arrays are initialized (try array('abc'....))... upvote anyway because its probably what OP wants –  Daniel Sloof Apr 11 '11 at 9:16
1  
@Daniel - yeah, I was rushing it a bit. heh. Fixed it up. –  Spudley Apr 11 '11 at 9:21
5  
Bravo :) +1 for one line answer $js_array = json_encode($php_array); –  Muhammad Riyaz May 11 '13 at 20:32
    
@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 –  Growler Jan 16 '14 at 3:45
    
@Growler: I'd need to see more of the code to be able to diagnose that. Perhaps you'd be better off asking it as a fresh question on SO. –  Spudley Jan 16 '14 at 7:24

Dumb and simple :

var js_array = [<?php echo '"'.implode('","', $php_array).'"' ?>];
share|improve this answer
1  
Just out of curiosity: what would happen when string contains quote , double quotes and/or comma? –  Nis Jun 30 '14 at 22:35
3  
indeed it is dumb :) Please first escape your data. –  Sorin Trimbitas Jul 21 '14 at 11:08
    
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
1  
One of the reasons may be shortness and simplicity of usage. I like this way and use it often, +1 –  Piero Aug 21 '14 at 15:37

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>
share|improve this answer

You do not have to call parseJSON since the output of json_decode 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>
share|improve this answer

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"

share|improve this answer

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);?>');
share|improve this answer

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());
share|improve this answer

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.

share|improve this answer

It can be done in a safer way, with only 1 line of code.

If your PHP array contains special characters, you need to use rawurlencode() in PHP and then use decodeURIComponent() in JS to escape those. And parse the JSON to native js. Try this:

var data = JSON.parse(decodeURIComponent("<?=rawurlencode(json_encode($data));?>"));
console.log(data);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.