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

Generative AR Shopping Apps 2026 67% Conversion Boost

  AI Agent Mobile Apps 2026 $2.3M ARR in 90 Days (Complete Guide) The 73% Cart Abandonment Problem You’re Solving…

Shafeeq Khan
January 31, 2026

AI Agent Mobile Apps 2026 $2.3M ARR in 90 Days (Complete Guide)

  AI Agent Mobile Apps 2026 $2.3M ARR in 90 Days (Complete Guide) The $2.3M ARR Problem You’re Solving  …

Shafeeq Khan
January 30, 2026

Top 12 AI App Development Trends 2026 Build $10M ARR Apps Agencies Are Charging $500K To Create

  Top 12 AI App Development Trends 2026 Build $10M ARR Apps Agencies Are Charging $500K To Create Trend #1…

Shafeeq Khan
January 26, 2026
, , ,

Leave a Reply

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