How to convert php array to javascript array

You can convert php arrays into javascript using php’s json_encode()* function:
Example:

$php_array =>array(
		'usd'=>500,
		'sgd'=>500,
		'cad'=>500,
		'eur'=>200,
		'cny'=>500
	)

To use the array, remember do JSON.parse():

var js_array = <?php echo json_encode($php_array ); ?>;
var newArray = JSON.parse(js_array);

To use the array, jquery $.each is easy to loop and retrieve the information:


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

$.each(js_array, function(currency, value) {
	//do your stuff here
}

By Keenlio, March 11, 2014

What do you think?

Leave a Reply

Your email address will not be published. Required fields are marked *


nine − = 6

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>