Convert php array to Javascript

460,028

Solution 1

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), ';';

Solution 2

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)

Solution 3

Dumb and simple :

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

Solution 4

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>

Solution 5

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:
460,028

Related videos on Youtube

user663878
Author by

user663878

Updated on September 27, 2021

Comments

  • user663878
    user663878 over 2 years

    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"
    ];
    
    • T.J. Crowder
      T.J. Crowder about 13 years
      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.)
  • Daniel Sloof
    Daniel Sloof about 13 years
    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
  • Spudley
    Spudley about 13 years
    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!
  • hakre
    hakre about 11 years
    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
  • Udo G
    Udo G about 11 years
    You're right. However, the code above has been used/tested for years in two large projects.
  • hakre
    hakre about 11 years
    php.net/array_map - and implode uses values only so already ignoring keys.
  • Udo G
    Udo G about 11 years
    Yes, that's intentional. Check the original question.
  • Udo G
    Udo G about 11 years
    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.
  • Spudley
    Spudley about 11 years
    @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.
  • user3871
    user3871 over 10 years
    @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
  • Nis
    Nis almost 10 years
    Just out of curiosity: what would happen when string contains quote , double quotes and/or comma?
  • Ben Rogmans
    Ben Rogmans almost 10 years
    If your PHP array contains special characters, this will go wrong. You can escape special characters using urlencode() functions. See my answer: stackoverflow.com/questions/5618925/…
  • Spudley
    Spudley almost 10 years
    @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.
  • cjbarth
    cjbarth over 9 years
    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.
  • Fr0zenFyr
    Fr0zenFyr almost 9 years
    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.
  • Eric
    Eric over 8 years
    that loop is terrible
  • Dipesh KC
    Dipesh KC over 8 years
    Well that was for demonstration purpose :)
  • Dipesh KC
    Dipesh KC over 8 years
    @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.
  • Heitor
    Heitor about 7 years
    Please nevermind!! Now we can just use this: json_encode($array, JSON_PRETTY_PRINT); and be happy!
  • Patrick Moore
    Patrick Moore about 6 years
    Just to point out that json_encode define a JavaScript object, NOT an array.
  • Spudley
    Spudley about 6 years
    @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.
  • oldboy
    oldboy almost 6 years
    is it insecure to simply swap over the values (i.e. echo "jsArray.push(\"" . $result[$i]["column_name"] . "\");";) ??????
  • Hammad Khan
    Hammad Khan over 5 years
    works better for unicode characters (urdu in my case)
  • Tomas Crofty
    Tomas Crofty almost 5 years
    The method @MohammadKawsara used works best for me obviously if you trust the user data.
  • Peter Lenjo
    Peter Lenjo about 4 years
    ...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.
  • Mik
    Mik about 4 years
    sure, but my way is the fastest of all suggestions on this page. Sometimes, speed could be an important factor.
  • A. D'Alfonso
    A. D'Alfonso almost 4 years
    Already upvoted this in 2018... I'd like to upvote again but can't
  • Bi Wu
    Bi Wu over 3 years
    Thanks, this worked well even for mixed object array. Very simple and efficient!