Assign PHP Array to Javascript Array

I am describing here a very useful method for getting the values of a PHP array in JavaScript.

For this we need to assign the PHP array values to a array in JavaScript.

<?php
$a = array('A','B','C');
?>
<html>
<head>
<title>Assign PHP Array to Javascript Array</title>
<script language="javascript"> 
	function showValues(){
		var a=new Array;
	<?php
		for($i=0;$i<count($a); $i++)
                {
			echo "a[$i]='".$a[$i]."';\n";
		}			
	 ?>
		for(i=0;i<a.length;i++)
			alert(a[i]);
	}
</script>
</head>
<body onload="showValues()">
</body>
</html>

11 thoughts on “Assign PHP Array to Javascript Array

  1. Why does your code ‘converting array from php to javascript’ not work (at least not show the values) when instead of array (‘A’,’B’,..) I fill the array with a file on the server: $a=file(‘tekst1.txt’) ?

  2. json is better. see bellow

    Assign PHP Array to Javascript Array

    function showValues(){
    var a=
    }

Leave a Reply to Srichakram Cancel reply

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

Scroll to top