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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.