-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
1
  • 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... Commented Mar 29, 2019 at 21:58

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for help bro !!
Sure, it was ... simple for me. I thought about using something fancy like array_walk, actually I have an idea
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

Comments

Your Answer

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