devendra
devendra

Reputation: 137

Printing values separated by space

I have a foreach loop which prints values of two variables:

$Var1 = '';
$Var2 = '';
foreach($variable as $key => $value)
{
   $Var1 .= $value->Id;
   $Var2 .= $value->Name;
}
echo $Var1;
echo $Var2;

If the loop runs 3 times, the result is:

Var1_value_1 Var1_value_2 Var1_value_3

Var2_value_1 Var2_value_2 Var2_value_3

But I want the following:

Var1_value_1 Var2_value_1 Var1_value_2 Var2_value_2 Var1_value_3 Var2_value_3

Upvotes: 1

Views: 67

Answers (1)

Ruslan Osmanov
Ruslan Osmanov

Reputation: 21522

If $variable is an array of objects with properties Id and Name, then you can print it this way:

$a = [];
foreach ($variable as $key => $value) {
   $a [] = $value->Id . ' ' . $value->Name;
}
echo implode(' ', $a);

where we simply concatenate the strings, push them into the $a array, then build the final string with implode.

Or even this way:

echo implode(' ', array_map(function ($v) {
  return $v->Id . ' ' . $v->Name;
}, $variable));

array_map applies the callback for each array item ($v). The callback returns modified item, the result of concatenation. Finally, the items of the new array are joined by implode.

Upvotes: 4

Related Questions