Pass PHP array as argument to JavaScript function

We all know that, we widely use JavaScript in our PHP page to perform some task. Those tasks could be either any small calculation or anything else. We know that we use array in PHP for our tasks. Some time it’s a requirement to use PHP array into JavaScript function. So I write this blog to fulfill that requirement.

There are two ways to pass the PHP array to JavaScript function as arguments. I have explained both of them here.

Method 1: USE JSON_ENCODE

First method is to convert the PHP array into JSON_ENCODE so that function that receives that array use as a JavaScript array. Complete example is given as follows:

<script type="text/javascript">
function displayarrayelement(demoarray)
{
	for(i=0;i< demoarray.length;i++) 
	{
alert(demoarray [i]); 
}
}
</script>
<?php
	$newarray = array();
	For($i = 10; $i<100; $i=$i+10)
	{
		$newarray [] = $i;
	}
?>
<a onclick="displayarrayelement(<?php echo json_encode($newarray) ?>);"> Array in JavaScript </a>

Method 2: Manually make PHP array like JavaScript array (use implode and split)

In Second method, we make the PHP array format like the JavaScript array manually. So the function direct use that array. Complete example is given as follows:

<script type="text/javascript">
function displayarrayelement(demoarray)
{
	demoarray = demoarray.split(",");
	for(var i=0;i<demoarray.length;i++) 
	{
		alert(demoarray [i]); 
	}
}
</script>
<?php
	$newarray = array('a','b','c');
	$mov_str = implode(",", $newarray);
?>
<a href="#" onclick="displayarrayelement('<?php echo $mov_str ?>');"> Array in JavaScript </a>

Hope this will help you as it did to me.
Thanks.

Speak Your Mind

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: