Croo
Croo

Reputation: 1371

Order-safe value passing from php to javascript

If I pass an array from php to js:

 var array = <?php echo json_encode($array); ?>;

Is it true that the ith element js array and the php array will refer to the same data?

Upvotes: 0

Views: 78

Answers (2)

bfavaretto
bfavaretto

Reputation: 71939

I believe the answer is yes for index-based arrays. On associative arrays, that translate to js objects, what json_encode does doesn't really matter, as JavaScript does not guarantee any particular key order when iterating over the keys (with for..in).

Upvotes: 1

bwoebi
bwoebi

Reputation: 23787

what are you trying here? mixing php and js?

You should use the function's parameter you pass: e.

var someArray = <?php echo json_encode($array); ?>;

for(var i = 0; i < someArray.length; i++) {
    infoWindow.setContent(createDivForElement(someArray[i]) );
}

function createDivForElement(e) {
    var result = '<div>';
    result += '<img src=' + e.thumbail + '/>'; 
    result += '</div>'
    return result;
}

You already pass someArray[i], you can address inside of the function with e. Then you don't need to involve any PHP in the function. You only need PHP here to pass the data to JS.


Always keep in mind that once you put PHP somewhere in, it won't change on the client-side.

Upvotes: 1

Related Questions