search
top

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 Responses to “Assign PHP Array to Javascript Array”

  1. Pragnesh says:

    Code is not complete, please share the complete code

  2. poorang says:

    it worked for me…
    thanks.

  3. a.g.sciarone says:

    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’) ?

  4. ajesamson says:

    json is better. see bellow

    Assign PHP Array to Javascript Array

    function showValues(){
    var a=
    }

  5. melacroso says:

    you absolute ripper! helped me out a treat! what a ledge!! cheers

  6. Srichakram says:

    A simple solution. Works perfect!!

    Thanks

  7. Pravin S Gaikwad says:

    its working, thanks

  8. funker says:

    var jsarray = ;

  9. stefenjun says:

    may be JSON is better choose.

Leave a Reply

top