-1

I have a table and in the table I have a column that shows details of uploaded files.

enter image description here

Like pdf, ppt, pdf.

With help of this link I convert my string into array.

So if I have ppt pdf ppt doc image it is converted into

Array ( [ppt] => 2 [pdf] => 1 [doc] => 1 [image] => 1 )

How can I convert this array into the following string?

2 ppt + 1 pdf + 1 doc + 1 image
mkrieger1
  • 14,486
  • 4
  • 43
  • 54
  • `so it is possible that this array convert into my below string` - yes, you can do it with a simple foreach loop. What have you tried... – ArtisticPhoenix Mar 29 '19 at 21:58

2 Answers2

2

I would do it this way

$array=["ppt" => 2,"pdf" => 1,"doc" => 1,"image" => 1 ];

$implodable=[];
foreach($array as $k=>$v){
    $implodable[] = "$v $k";
}

echo implode(" + ", $implodable);

Output

2 ppt + 1 pdf + 1 doc + 1 image

Using an Array and implode, means you don't have to trim anything off the end.... :)

Sandbox

ArtisticPhoenix
  • 20,856
  • 2
  • 21
  • 35
1

You can do this with a foreach loop:

$result = null;

foreach ($array as $key => $value){ //Loops through array
    $result .= $value . ' ' . $key . ' + '; //Adds key and array to string
}

$result = substr($result, 0, -3); //Removes last 3 characters

Source: foreach

Mark Mueller
  • 517
  • 5
  • 15