Convert PHP Array into JavaScript Array.

Code

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.

Shiv kumawat

Executive Director & CEO

"Shiv kumawat is the Executive Director and CEO of Eoxys It Solution LLP and the strategic mind behind the company"s growth. His expertise in operational efficiency and team leadership empowers his colleagues to excel and innovate.”

Latest Posts

Reinventing Everyday Life: The Rise of Artificial Intelligence in Finance for 2025

  Reinventing Everyday Life: The Rise of Artificial Intelligence in Finance for 2025 A New Financial Landscape Artificial intelligence isnʼt…

sakshi
August 14, 2025

AI in Retail USA Redefining Shopping, Operations, and Experiences in 2025

  AI in Retail USA: Redefining Shopping, Operations, and Experiences in 2025 How Artificial Intelligence Is Changing Retail in the…

sakshi
August 11, 2025

AI in Healthcare USA Transforming Patient Care and Operations in 2025

  AI in Healthcare USA: Transforming Patient Care and Operations in 2025 The Rise of AI in Healthcare Across the…

sakshi
August 7, 2025
, , ,

Leave a Reply

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