1

I have this PHP array:

$teams = array(
    "img1" => "img/img1.jpg",
    "img2" => "img/img2.jpg",
    "img3" => "img/img3.jpg",
    ...
);

Is there any way to get the same array in Javascript? By same array I mean a array with key => values?

0

5 Answers 5

4

There are no associate arrays in javascript, but you can use objects with a key.value pair.

var obj = {};
obj.myNewKey = myNewValue;

You can also refer to these object properties in the following way:

obj['myNewKey'] = myNewValue;

Just keep in mind that although it looks like an associative array, it is actually an object.

There is also this way:

var obj = {
  myNewKey:"myNewValue",
  "myOtherKey":"myOtherValue"
};
Sign up to request clarification or add additional context in comments.

Comments

1

Do you mean echo "var teams = ".json_encode($teams);

Comments

0

No. Arrays are indexed numerically.

However, objects allow string keys to values, similar to an associative array (but not quite - it is unordered and has none of the Array methods).

var teams = {
    "img1":"img/img1.jpg",
    "img2":"img/img2.jpg",
    "img3":"img/img3.jpg"
};

Comments

0
var a={"key":"value","key2":"value2"}

Comments

0

if you wish to have the exact array from your php transfered to your script tag in html you could pass it as a json string in the following way:

<html>
    <head>
        <script>
         // some js code here
         var teams = <?php echo json_encode($teams); ?>;
         // some other js code
        </script>
    </head>
    <body>
        page html content here
    </body>
<html>

3 Comments

@mplungjan, to evaluate the json string and convert it to an JS object, or is there a better way to make ?
php.net/manual/en/function.json-encode.php se my suggestion. No need to do anything except put a var varname = in front of it
Okay, I got it now, thanks, I've edited my answer, if you don't mind, please remove the downvote

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.