Jump to content

Archived

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

paul2463

Function Help

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?

Share this post


Link to post
Share on other sites
You don't really need a function to do this:
[code]<?php
$instr - array('Saab','Volvo','BMW');
$jsstr = '"' . implode('","',$instr) . '"';
echo $jsstr;
?>[/code]

Ken

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites

×

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.