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 and GenAI development company he has led since 2009. Eoxys builds custom AI, web and mobile applications for businesses worldwide. Shiv writes about AI app development, generative AI for business, and building software products that deliver real results. Connect with him on LinkedIn: https://www.linkedin.com/in/shiv-kumawat-eoxys/

Latest Posts

Isometric illustration of an online store connected to three AI shopping agents handling product discovery, chat and checkout

AI Shopping Agents for E-commerce: Get Your Store Ready Now

This is the first holiday season where AI shopping agents are a real sales channel. Shopify’s 2026 holiday research, published…

Shiv Kumawat
October 7, 2026
Build vs buy AI hiring software: custom-built blocks versus a ready-made hiring dashboard, balanced by AI

Build vs Buy AI Hiring Software: A 2026 Decision Guide

Recruiting is where most companies meet AI first. In SHRM’s 2025 Talent Trends research, 51% of organizations said they use…

Shiv Kumawat
October 6, 2026
On-device AI in mobile apps: models running locally on the phone

On-Device AI Mobile Apps in 2026: Benefits, Trade-offs and Use Cases

  On-device AI means the model runs on the user’s phone instead of on your servers. Since September 2025, every…

Shafeeq Khan
February 18, 2026
,

Leave a Reply

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