-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
  • 19,194
  • 5
  • 54
  • 65
  • `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
  • 21,464
  • 2
  • 24
  • 38
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

Haley Mueller
  • 487
  • 4
  • 16