Naveen mutharasi
Naveen mutharasi

Reputation: 105

how to implode multiple values?

How to implode multiple values?

I have following implode method:

$a = array("".$_POST['questionid']."","$qid");
$b = array("".$_POST['AnswerID']."","$ans");
$c = array("".$_POST['timetaken']."","$time");

$comma = implode(",",$a);
echo "$comma";

it gives:1,2 and print a,b value

    $comma = implode(",",$a);
    echo "$comma";
    $comma1 = implode(",",$b);
    echo "$comma1";

it gives:1,34,2 how do i print 1,2,3,4

Upvotes: 3

Views: 6475

Answers (3)

devpro
devpro

Reputation: 16117

Use array_merge for $a and $b it will give you 1,3,4,2 after implode for sequence use sort() function.

Example:

$a = array($_POST['questionid'],$qid);
$b = array($_POST['AnswerID'],$ans); 

// merge both
$merge = array_merge($a,$b);

// for ASC order
sort($merge);
$comma = implode(",",$merge); 
echo $comma; //1,2,3,4

Issue in your code:

You are not using comma between both implode() so you are getting 1,34,2.

Now if you need to print in sequence you need to use sort();

Upvotes: 1

Hassaan
Hassaan

Reputation: 7672

Why don't you add , by your self to variable $b

Change from

$comma1 = implode(",",$b);

into

$b[0] = ",".$b[0];
$comma1 = implode(",",$b);
echo $comma1;

2nd method: - Secondly you can marge arrays by using array_merge() then you can implode it via ,

$comma = implode(",", array_merge($a, $b));
echo $comma;

Upvotes: 4

Nijraj Gelani
Nijraj Gelani

Reputation: 1466

You can use array_merge() to first merge all arrays and then implode them. Like this :

$comma = implode(",", array_merge($a, $b));

Upvotes: 2

Related Questions