web analytics

How to pass or use PHP array/variable in JavaScript?

Multidimensional PHP arrays are similar to multidimensional JSON objects. So shouldn’t be there a way to use a multidimensional PHP array in Javascript? Obviously, and there are ways. For example you can use AJAX to make a request and get the PHP array back in JSON format. However, why to make an AJAX call if the array is ready to be used already? Right.  

If the PHP array is ready to be used in Javascript already, then just simply echo the PHP array in a Javascript variable as follows.  

<?php
$settings = array(
	'id' => 'mydemoWidget',
	'status' => 'active',
	'configuration' => array(
		'title' => 'Demo Title',
		'style' => array(
			'background-color' => '#fff',
			'border' => true,
		),
		'content' => array(
			'category' => null,
			'page' => 5,
			'tags' => array(5,4,3),
			'start' => 0,
			'total' => 10
		),
	)
);
?>
<script type="text/javascript">
	var $settings = <?php echo json_encode($settings)?>;
</script>

So that’s it.

You can also ECHO any PHP variable to JS variable. Just don’t forget to use quotation around the PHP tag in case of string, json_ecnode the variable if it is an array.

<?php
$an_array = array();
$a_string = "I am string";
$a_numeric = 5;
?>
<script type="text/javascript">
	var $an_array = <?php echo json_encode($an_array)?>;
	var $a_string = "<?php echo $a_string?>";
	var $an_array = <?php echo $a_numeric?>;
</script>

Please follow and like us:
Pin Share

Comments are closed.

RSS
Follow by Email
Scroll to Top