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

AI in Fitness & Gym Booking Apps Smart Training and Wellness in 2026

  AI in Fitness & Gym Booking Apps Smart Training and Wellness in 2026 The Intelligent Fitness Revolution Fitness and…

Shafeeq Khan
January 8, 2026

AI in Pet Care & Veterinary Apps – Smart Pet Wellness in 2026

  AI in Pet Care & Veterinary Apps – Smart Pet Wellness in 2026 The Pet Tech Revolution Pet ownership…

Shafeeq Khan
January 7, 2026

The Future of Sustainable AI Green Computing Trends Shaping 2026

  The Future of Sustainable AI Green Computing Trends Shaping 2026 AI’s Environmental Reckoning As AI adoption explodes in 2026,…

Shafeeq Khan
January 6, 2026
, , ,

Leave a Reply

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