Forum Moderators: coopster

Message Too Old, No Replies

implode() function

joining values in quoted string

         

dbarasuk

6:14 pm on Apr 8, 2008 (gmt 0)

10+ Year Member



Hello
Just a small question:

If I do

<?php
$array = array('Me', 'You', 'She');
$new_array=implode(',', $array);
print_r($new_array); // output 'Me,You,She'
?>

My qusetion is:

How can I use the implode function in this case to output 'Me','You','She'?

I tried doing print_r('","', $new_array); but there was no opening quote for the first value and no closing quote for the last one.

PHP_Chimp

6:48 pm on Apr 8, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member




$array = array('Me', 'You', 'She');
$output = "'"; // add starting '
$length = count($array)-1; // as we need the length of the keys, not the counted length
$i = 0;
while ($i <= $length) { // for all elements other than the last add a , after the value
$output.= "$array[$i], ";
$i++
}
if ($i == $length) { // for the last element close the '
$output.= "$array[$i]'";
}
echo $output;

As if you want 'Me, You, She' you need to add the ''s manually and add the , to every element other than the last.

<edit>
Durr...maybe I should redo that to get what you wanted.


// answer == 'Me','You','She'
$array = array('Me', 'You', 'She');
$output = '';
$length = count($array)-1;
$i = 0;
while ($i <= $length) {
$output.= "'$array[$i]', ";
$i++
}
if ($i == $length) {
$output.= "'$array[$i]'";
}
echo $output;

That should do what you wanted...hopefully...this time ;)

[edited by: PHP_Chimp at 6:55 pm (utc) on April 8, 2008]

cameraman

7:57 pm on Apr 8, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



$new_array = "'" . implode("','", $array) . "'";

dbarasuk

11:30 pm on Apr 8, 2008 (gmt 0)

10+ Year Member



I'll adopt the last solution since shortest.
kind regards,
many thks.

PHP_Chimp

9:33 am on Apr 9, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Ye I would do that as well.

I knew that there was a better solution, just couldn't think of the obvious.
I'm glad that someone else was more awake ;)