Home > Backend Development > PHP Tutorial > How Can I Convert a PHP Array to a JavaScript Array Using JSON?

How Can I Convert a PHP Array to a JavaScript Array Using JSON?

Mary-Kate Olsen
Release: 2024-12-19 00:45:10
Original
701 people have browsed it

How Can I Convert a PHP Array to a JavaScript Array Using JSON?

Convert PHP Array to Javascript

Problem:

How can PHP arrays be converted into Javascript arrays that follow a specific format, such as the one provided for city names?

Solution:

While the provided PHP and Javascript arrays are not directly related, PHP offers the json_encode() function to convert arrays into Javascript code in JSON (JavaScript Object Notation) format.

<?php
$php_array = array('001-1234567', '1234567', '12345678', '12345678', '12345678', 'AP1W3242', 'AP7X1234', 'AS1234', 'MH9Z2324', 'MX1234', 'TN1A3242', 'ZZ1234');
$js_array = json_encode($php_array);
echo "var javascript_array = " . $js_array . ";\n";
?>
Copy after login

The output will be the following Javascript code:

var javascript_array = ["001-1234567","1234567","12345678","12345678","12345678","AP1W3242","AP7X1234","AS1234","MH9Z2324","MX1234","TN1A3242","ZZ1234"];
Copy after login

Note that json_encode() is available in PHP versions 5.2 and later. For older PHP versions, alternative functions may be available in the PHP manual.

The above is the detailed content of How Can I Convert a PHP Array to a JavaScript Array Using JSON?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template