2

I have this array and I want to convert it into string.
I try to get string from php implode() function but could not get the desired result.
The output I want is arraykey-arrayvalue,arraykey-arrayvalue,arraykey-arrayvalue and so on as long as array limit end.

 Array ( [1] => 1 [2] => 1 [3] => 1 )
 $data = implode(",", $pData);
 //it is creating string like
 $data=1,1,1;
 // but i want like below 
 $string=1-1,2-1,3-1; 

3 Answers 3

6

You could just gather the key pair values inside an array then implode it:

foreach($array as $k => $v) { $data[] = "$k-$v"; }
echo implode(',', $data);
Sign up to request clarification or add additional context in comments.

Comments

2

You can also use array_map function as

$arar = Array ( '1' => 1 ,'2' => 1, '3' => 1 );
$result = implode(',',array_map('out',array_keys($arar),$arar));
function out($a,$b){
   return $a.'-'.$b;
}
echo $result;//1-1,2-1,3-1; 

Comments

1

This can be done using the below code:

$temp = '';
$val = '';
$i=0;
foreach ($array as $key => $value)
{
    $temp = $key.'-'.$val;
    if($i == 0)
    {
        $val  = $temp; // so that comma does not append before the string starts
        $i = 1;
    }
    else
    {
        $val = $val.','.$temp;
    }
}

1 Comment

Please use array_map function and finally implode it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.