Jump to content

Function Help


paul2463

Recommended Posts

Hello People
I am trying to write a function that produces a string variable in a form, that if it is written to html, it will be accepted by javascript for an array object, the format that is accepted is as follows
[code]"Saab","Volvo","BMW"[/code]
my function code is as follows
[code]
function arraytojs($array){
$str = "";
foreach ($array as $val):
  $str .=  "'".$val."',";
endforeach;
$str = rtrim($str, ",");
return $str;
}[/code]

my problem is that this produces a string in the form of
[code]
'Saab','Volvo','BMW'[/code]

I would like the single quotes to be double quotes that will make it compatible to a javascript array call, but when it try and rewrite the function with double quotes in the place of the single quotes I get errors thrown up, I am struggling to figure it out. any help please?
Link to comment
https://forums.phpfreaks.com/topic/14035-function-help/
Share on other sites

Just as a note for future: if you want to use quotes inside a strong (So double quotes inside a doube-quoted string or single-quote inside single-quoted) then you'll have to escape them using the backslash character.

So this will throw an error:
[code]$str = "  "  ";[/code]

But this will not:
[code]$str = "  \"  ";[/code]

Because we have told it that the quote in the middle is literally in the string.
Link to comment
https://forums.phpfreaks.com/topic/14035-function-help/#findComment-54953
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.