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
Mary-Kate OlsenOriginal
2024-12-19 00:45:10704browse

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";
?>

The output will be the following Javascript code:

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

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!

Statement:
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