Jump to content

transform php array in a javascript array! can it be done or not?


stefffff

Recommended Posts

how can i use a javascript variable in php or is it possible to transform a php array in a javascript array?

 

let's say i have the following dynamically generated php array :

$r = array('p1.jpg,p2.jpg,p3.jpg');

 

meaning that

 

$r[0] = 'p1.jpg';

$r[1] = 'p2.jpg';

$r[2] = 'p3.jpg';

 

how can i transform this array to be used in javascript? i want the javascript array to get the php array values.... and get something like this... is there a way?

 

var r = array();

r[0] = 'p1.jpg'

r[1] = 'p2.jpg'

r[2] = 'p3.jpg'

 

Firstly you need a valid php array, then simply loop through it and right it into a javascript array.

 

<?php

$r = array('p1.jpg','p2.jpg','p3.jpg');

echo "<script type=\"text/javascript\">";
echo "var r = new Array();";
foreach ($r as $k => $v) {
  echo "r[$k] = \"$v\"";
}
echo "</script>";

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.