Tell me more ×
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
2  
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
2  
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

6 Answers

up vote 10 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
4  
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 at 9:32
You're right. However, the code above has been used/tested for years in two large projects. – Udo G Feb 19 at 13:44
php.net/array_map - and implode uses values only so already ignoring keys. – hakre Feb 19 at 14:41
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 at 19:39
show 2 more comments

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
@Daniel - yeah, I was rushing it a bit. heh. Fixed it up. – Spudley Apr 11 '11 at 9:21
2  
Bravo :) +1 for one line answer $js_array = json_encode($php_array); – Riyaz Muhammed May 11 at 20:32

Dumb and simple :

var js_array = [<?php echo '"'.implode('","', $php_array).'"' ?>];
share|improve this answer

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

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

This si 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

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.