Jump to content


Photo

Function Help


  • Please log in to reply
2 replies to this topic

#1 paul2463

paul2463
  • Members
  • PipPipPip
  • Advanced Member
  • 955 posts
  • LocationUK

Posted 08 July 2006 - 05:29 PM

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
"Saab","Volvo","BMW"
my function code is as follows
function arraytojs($array){
 $str = "";
 foreach ($array as $val):
   $str .=  "'".$val."',";
 endforeach;
 $str = rtrim($str, ",");
 return $str;
}

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

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?
you cannot affect the past but you can ruin a perfectly good present by worrying about the future

*********************************************************************
The <A HREF="http://www.php.net/d...php">MANUAL</A> is actually a useful resource

#2 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 08 July 2006 - 05:37 PM

You don't really need a function to do this:
<?php
$instr - array('Saab','Volvo','BMW');
$jsstr = '"' . implode('","',$instr) . '"';
echo $jsstr;
?>

Ken

#3 ShogunWarrior

ShogunWarrior
  • Members
  • PipPipPip
  • Advanced Member
  • 528 posts
  • LocationIreland

Posted 08 July 2006 - 10:19 PM

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:
$str = "  "  ";

But this will not:
$str = "  \"  ";

Because we have told it that the quote in the middle is literally in the string.
<a href="http://www.daviddora...nmedia.com/">My New Site/Blog</a> | <a href="http://www.daviddora...m/check/">Check your page for broken links/images/scripts</a>

Zend Certified Engineer
Follow me on Twitter: http://twitter.com/davidd




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users