Creating a JavaScript array from a PHP array

Suppose I have the line $var :

 //php code $var = "hello,world,test"; $exp = explode(",",$var); 

Now I get the array as exp[0],exp[1],exp[1] as 'hello' , 'world' and 'test' respectively.

I want to use this value in javascript in this:

 var name = ['hello','world','test']; 

How can I generate this javascript in PHP?

+4
source share
2 answers

I would think json_encode would be the most reliable and easiest way.

eg.

 $var = "hello,world,test"; $exp = explode(",",$var); print json_encode($exp); 
+19
source

Karl B's answer is better - use it!

It would not be easier:

 $var = "hello,world,test"; $var = str_replace(",", "','", $var); 

Then wherever you spit out JavaScript (assuming you can use PHP there):

 var name = ['<?php echo $var; ?>']; 

This does not apply to quotation marks, but if you want it, you better use fgetscsv et et al.

If you intend to use explode , you can use the other half, implode , like this in your output:

 var name = ['<? php echo implode("','", $var); ?>']; 
+4
source

Source: https://habr.com/ru/post/1298998/


All Articles