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

Smarter Learning for a Smarter Era: How AI Is Transforming Learning Management Systems (LMS) in 2025

  Smarter Learning for a Smarter Era: How AI IsTransforming Learning Management Systems(LMS) in 2025 From Static Systems to Intelligent…

Shafeeq Khan
October 3, 2025

AI Overviews and Google Search: What Businesses Need to Know in 2025

  AI Overviews and Google Search: What Businesses Need to Know in 2025 Entering the Age of AI Overviews The…

Shafeeq Khan
September 23, 2025

Ride Smarter: How AI Is Transforming Cab Apps in the USA for 2025

  Ride Smarter: How AI Is Transforming Cab Apps in the USA for 2025 The New Pulse of Urban Travel…

Shafeeq Khan
September 20, 2025
, , ,

Leave a Reply

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