4

I want to convert the following PHP code to JavaScript, This is an array of key/value pairs in PHP:

PHP code:

$countries = array("AF"=>"AFGHANISTAN","AX"=>"ALAND ISLANDS");

What's the best way to do this in jQuery or JavaScript?

1
  • 1
    Note also that jQuery IS JavaScript, so there is no such thing as a jQuery array, only a JS array. Commented Aug 22, 2012 at 10:23

3 Answers 3

4

javascript doesn't have an associative array (like in PHP, your example above), instead, we call it javascript object:

var countries = {
    'AF': 'AFGHANISTAN', 
    'AX': 'ALAND ISLANDS'
};
Sign up to request clarification or add additional context in comments.

Comments

1
var countries = {
  "AF": "AFGHANISTAN",
  "AX": "ALAND ISLANDS"
}

Then, to get the value for a given key, use one of the following:

var af = countries["AF"];
var ax = countries.AF;

Comments

0

Use json_encode():

<script>
    var countries = <?php echo json_encode($countries); ?>;
</script>

That's what will be stored in countries:

{
    AF : "AFGHANISTAN",
    AX : "ALAND ISLANDS"
}

If you just want to reproduce such a data structure in JS, use objects as stated in the other posts.

1 Comment

Sorry but the edit changes the meaning of my original answer, and makes not much sense at all - no strings are involved at all, I just go from PHP array to JS object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.