Convert PHP Array into JavaScript Array.

Code

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.

Related reading:

Shiv Kumawat

Executive Director & CEO

Shiv Kumawat is the CEO of Eoxys IT Solution LLP, the Jaipur-based IT company he has led since 2009. An AI & IT Solutions Consultant with 16+ years of experience, he works with startups and enterprises to turn ideas into market-ready SaaS platforms, mobile apps and AI-driven solutions. His team has delivered 700+ projects across SaaS, mobile and web apps, automation and AI. He previously served as Chief Technology Officer for a US company.

Latest Posts

Colour photograph illustrating the Eoxys blog post 'Computer-Use AI Agents: Automate Old Software Without an API', used as the featured image for computer use ai agents.

Computer-Use AI Agents: Automate Old Software Without an API

Every business has a task like this: an employee logs into a government portal, a supplier site or a 15-year-old…

Shafeeq Khan
November 16, 2026
Colour photograph illustrating the Eoxys blog post 'Product Feed Optimization for ChatGPT Shopping and AI Mode', used as the featured image for product feed optimization ai shopping.

Product Feed Optimization for ChatGPT Shopping and AI Mode

When a shopper asks ChatGPT or Google AI Mode for “the best running shoes under ₹6,000 for flat feet”, the…

Shafeeq Khan
November 15, 2026
Colour photograph illustrating the Eoxys blog post 'Hire an AI Product Manager: Skills, Salary and When You Need One', used as the featured image for hire ai product manager.

Hire an AI Product Manager: Skills, Salary and When You Need One

Your team can call a model API in an afternoon. Deciding what the AI feature should do, how good is…

Shafeeq Khan
November 14, 2026
,

Leave a Reply

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