Converting PHP Array Into a Javascript Array

Converting PHP Array Into Javascript Array

The purpose of this tutorial is to demonstrate how we can take an array from php and use it an array in Javascript. Here is the basics of the code. We have a web page with a list of entries. Each entry has a checkbox next to it and its value is the entry's id.

With Jquery, we use the change() function for the checkboxes. If a check box is selected or deselected and it is greater than 15, we use the alert() function to show the id of the changed checkbox.

Then, we use php / mySQL to make an array of names. To be useful in Javascript, we use the implode function to turn the array into a string that separates the names with commas.

Then, the $names_string variable is the new Javascript variable that is equal to the php string. We can use use the string, or convert it to an array with 'myArray = new Array(names_string);' or 'var myArray = $.makeArray(names_string);'.

Finally, the each() function is used to sort the array.

<script type="text/javascript">
$(document).ready(function(){
	$("input.check").change(function() {
	var value = $(this).val(); 
	
	var Class = $(this).attr('class');
	
	if(value > 15 && Class == "check"){
		//$(this).css("color", "red");
		alert(value);
		<?
		$command = "SELECT * FROM tablename ";
		$result = mysqli_query($db, $command);
		while ($row = mysqli_fetch_assoc($result)){
		//$val = $row['id'];
		$val = $row['firstname'];
		$names_array[] = $val;
		}
		## PHP Array to Javascript String
		$names_string = implode(",", $names_array); // create a string from the array of ids
		?>
		//alert ("<?php echo $names_string; ?>");
		names_string = "<?php echo "".$names_string.""; ?>"; // now the javascript variable is set
		alert (names_string);

		// sort through string  ie) if the value is in string		
		
        //PHP STRING to Javascript Array
		//myArray = new Array(names_string); //convert string to array method a
		var myArray = $.makeArray(names_string); //convert string to array method b 
		var myArray = names_string.split(','); // for names 
		$.each(myArray,  function(k, v){
    alert( "Key: " + k + ", Value: " + v );
	});
// sort through array and look for id in the array

	}	
	else {
	$(this).css("color", "#000000");
	}		
	});	
});		
</script>