Page 1 of 1
Converting php array to javascript array
Posted: Wed Dec 16, 2009 11:39 am
by code_worm
Hi, I want to create a javascript array that duplicates the values within a PHP array.
I have looked at many resources online, but due to little understanding i havent implemented them as of yet.
What i am asked to do is duplicate this php array to a javascript array within the head of my php page. Does this mean that it needs to be a function?
Most of the code i see is relevant to sql stuff, I would be very greatfull for your help or even relevant resources
Thanks cw
Re: Converting php array to javascript array
Posted: Wed Dec 16, 2009 11:44 am
by AbraCadaver
json_encode()
Re: Converting php array to javascript array
Posted: Wed Dec 16, 2009 11:49 am
by code_worm
Json_encode()
Just read up on it, it says that it returns a string on execution.
I want to return a populated array, do you mean to say populate the javascript array with json_encode() ?
My experiance in both javascript and php are limited sorry
Re: Converting php array to javascript array
Posted: Wed Dec 16, 2009 12:05 pm
by AbraCadaver
code_worm wrote:Json_encode()
Just read up on it, it says that it returns a string on execution.
I want to return a populated array, do you mean to say populate the javascript array with json_encode() ?
My experiance in both javascript and php are limited sorry
Yes (example):
Code: Select all
echo '<script type="text/javascript">'
'var myJSarray = ' . json_encode($myPHParray) . ';'
'</script>';
Re: Converting php array to javascript array
Posted: Wed Dec 16, 2009 12:33 pm
by code_worm
Thanks, I have never implemented this before.
Am i stupid in asking this, I am required to do this in the head section...
As this code goes in the head will it still work if the php array declaration is in the body. Does this mean i need to create a function?
Re: Converting php array to javascript array
Posted: Wed Dec 16, 2009 12:49 pm
by code_worm
What i am creating is a dynamic html page
If i create the javascript array within the head of my php page will i be able to acess this array through my js functions?