Convert PHP Array into JavaScript Array.


We can use PHP array in javascript. For this we have to convert PHP array ,whether the array type is a single or multidimensional or indexed or associative array,into JSON format Using php function json_encode().It’s mostly used when we have create API in PHP to transfer data form one server to other server because data format in JSON travel so fast compare to other format and easily accessible in PHP and Javascript.

PHP

$cars = array("Volvo", "BMW", "Toyota");

Javascript

<script>
var cars = <?php echo json_encode($cars); ?>
console.log(cars[2]); // Output will be: Toyota
alert(cars[1]); // Output will be: BMW
</script>

Multidimensional Array

PHP

$cars = array(
array('Brand'=>'Volvo', 'Year'=>'2016'),
array('Brand'=>'BMW', 'Year'=>'2017'),
array('Brand'=>'Toyota', 'Year'=>'2018')
);

Javascript

<script>
var cars = <?php echo json_encode($cars); ?>
console.log(books[0]['Brand']); // Output will be: Volvo
alert(books[1]['Year']); // Output will be: 2017
</script>

Enjoy.

, , ,

Leave a Reply

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