-1

I have an array like below;

$carsarray = array("audi","toyota","ford");

I want to generate a string like;

'audi','toyota','ford'

Using implode function like;

$cars = implode(",",$carsarray);

I get output like

audi,toyota,ford

To get my desired output, I use;

$cars = "";
foreach($carsarray as $car){
    $cars .= "'".$car."',";
}
$cars = rtrim($cars,","); // this gives me 'audi','toyota','ford'

But, is there any other better / efficient method other than using these foreach or while or some other loops? I mean, something like an implode function?

Alfred
  • 21,058
  • 61
  • 167
  • 249

3 Answers3

2

Try -

$cars = "'" . implode("','", $carsarray) . "'";
Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
1

You can use this

$cars = "'".implode("','",$carsarray)."'";

Armen
  • 4,064
  • 2
  • 23
  • 40
1

Try to use this:

$carsarray = array("audi","toyota","ford");
$your_result = "'";
$your_result .= implode("','",$carsarray);
$your_result .= "'";
devpro
  • 16,184
  • 3
  • 27
  • 38