Assertion:if you have a PHP array and need to convert it to a JavaScript array, that is, PHP provides a function that easily converts that PHP array to a JavaScript array. But before using this function, you need a few things, which first make sure you are using PHP version 5.2 or higher. Then use the
json_encode()library function to convert the PHP array to a JavaScript array.
Syntax:json_encode ($my_array) ;
Example 1:This example uses the json_encode() function to convert a PHP array to a JavaScript JSON object.
// Array in php
$myArr
=
array
(
’Geeks’
,
’GeeksforGeeks @ engineer.com’
);
?>
array
into JavaScript
array
->
Output:[email protected]
Example 2:Here you will see the conversion of a one-dimensional PHP array to a javaScript array using json_encode ($myArr)... By passing in a php array and then using json_encode, we convert it to a javascript array. < script type =
’text / javascript’
>
$php_array
=
array
(
’engineer’
,
’for’
,
’engineer’
);
$js_array
= json_encode (
$php_array
);
echo
"var javascript_array ="
.
$js_array
.
";"
;
?>
document.write (javascript_array [0]);
< / script >
Output:engineer
Example 3:Here you will see the conversion of a PHP multidimensional array to a javaScript array using json_encode ($myArr) . By passing in a php array and then using json_encode, we convert it to a javascript array.
< script type =
’text / javascript’
>
$php_array
=
array
(
array
(
’Geeks’
,
’ for @ example.com’
),
array
(
’ for’
,
’gfg @ example.com’
),
);
$js_array
= json_encode (
$php_array
);
echo
"var javascript_array ="
.
$js_array
.
";"
;
?>
document.write (javascript_array [0] [1]);
< / script >
Output:[email protected]
Note.It should be noted that the json_encode() function is only available in PHP 5.2 or later.