PHP Convert PHP Array To JavaScript Or Json Example

03-Apr-2023

.

Admin

PHP Convert PHP Array To JavaScript Or Json Example

Hello Friends,

In this post, i will show you convert php array to javascript or json. We will use how to convert php array to javascript or json. We will show how to pass a php array to a javascript function. This article will give you convert php array to javascript.

In this tutorial, I would like share with you to convert a php array to a valid json string for use in javascript. how to pass a php array to a javascript function.

Here i will give you many example how to convert php array to javascript or json.

So let's see bellow example:

Example : 1


<!DOCTYPE html>

<html>

<head>

<title>PHP Convert PHP Array To JavaScript Or Json Example - Nicesnippets.com</title>

</head>

<body>

<?php

// Converting PHP array into JavaScript array

$myArr = array('Nicesnippets', 'Aatman');

?>

<script>

var arr = <?php echo json_encode($myArr); ?>;

document.write(arr);

</script>

</body>

</html>

Output:

Nicesnippets,Aatman

Example : 2

<!DOCTYPE html>

<html>

<head>

<title>PHP Convert PHP Array To JavaScript Or Json Example - Nicesnippets.com</title>

</head>

<body>

<script type='text/javascript'>

<?php

// Multi-dimensional PHP array Example

$php_array = array(

array('Name', 'Aatman'),

array("<br>".'Email', 'aatman@gmail.com'),

);

$js_array = json_encode($php_array);

echo "var javascript_array = ". $js_array . ";\n";

?>

document.write(javascript_array);

</script>

</body>

</html>

Output:

Name,Aatman,

Email,aatman@gmail.com

I hope it can help you...

#PHP