paul2463 Posted July 8, 2006 Share Posted July 8, 2006 Hello PeopleI 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? Quote Link to comment https://forums.phpfreaks.com/topic/14035-function-help/ Share on other sites More sharing options...
kenrbnsn Posted July 8, 2006 Share Posted July 8, 2006 You don't really need a function to do this:[code]<?php$instr - array('Saab','Volvo','BMW');$jsstr = '"' . implode('","',$instr) . '"';echo $jsstr;?>[/code]Ken Quote Link to comment https://forums.phpfreaks.com/topic/14035-function-help/#findComment-54845 Share on other sites More sharing options...
ShogunWarrior Posted July 8, 2006 Share Posted July 8, 2006 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. Quote Link to comment https://forums.phpfreaks.com/topic/14035-function-help/#findComment-54953 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.