samyb8
samyb8

Reputation: 2588

Printing PHP array values in one single string

I have an array which I load as follows:

foreach ($_SESSION['cart'] as $item) 
{
  $pid = $item['itemId'];
  $q = $item['qty']; 
  $orderedItems[]=array('itemId'=>$pid,'qty'=>$q);
}

I now need to create a variable that will store the results of my array in a string just like this:

"For itemA ==> 2 sample
For itemB ==> 1 sample"

Upvotes: 0

Views: 48

Answers (2)

Barmar
Barmar

Reputation: 780889

$string = join("\n", array_map(function($x) {return "For $x[itemId] ==> $x[qty] sample";}, $orderedItems));

Upvotes: 1

bwoebi
bwoebi

Reputation: 23777

$string = "";
foreach ($orderedItems as $item)
    $string .= "For item{$item['itemId']} ==> {$item['qty']} sample\n";
$string = rtrim($string);

Upvotes: 0

Related Questions