Convert PHP Integers Array To Javascript Variables

Convert PHP Integers Array Into Javascript Array With Jquery

This tutorial shows how we can take an array of numbers from php and use it an array in Javascript. Here is how it works. 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 numbers. To be useful in Javascript, we use the implode function to turn the array into a string that separates the ids with commas. Then, the $ids_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(ids_string);' or 'var myArray = $.makeArray(ids_string);'. Then, the each() function is used to sort the array.

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

		// sort through string  ie) if the value is in string		
        //PHP STRING to Javascript Array
		//myArray = new Array(ids_string); //convert string to array method a
		var myArray = $.makeArray(ids_string); //convert string to array method b 
		var myArray = ids_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");