PHP array to JSON conversion

  • Favourite
Average Star Rating is 3.4 from the Total 8 Ratings

Sometimes, we have to transfer data from php to JavaScript or JavaScript to php. In that case we can use json_encode and json_decode function to convert data to on form to other. For example if you have a php associative array then you can convert it to JavaScript object literal. If it is a php numeric array then you can convert it to JavaScript numeric array the same way. This simple technique can be very useful specially in AJAX functionality! 

Copy and try this code in phpfiddle and press run.

	$product = array("p_id"=>1,"p_name"=>"Laptop");
	echo "<hr>";
	var product =<?php echo json_encode($product)?>;

Be the first to make a comment!