Chris
Chris

Reputation: 41

Print each 2 values of an array followed by an empty line

I have for instance this array:

myArray("key1"=>"value1", "key2"=>"value2", "key3"=>"value3", "key4"=>"value4", "key5"=>"value5", "key6"=>"value6");

I need to display the values of this array with an empty line each 2 values. I have tried the following:

function array_implode_with_value($array){
  $return = '';
  foreach ($array as $value){
    $return .= $value . PHP_EOL . PHP_EOL;
  }
  return $return;
}

$description = array_implode_with_value($myArray);

My function just add 2 line breaks after each value:

value1

value2

value3

value4

value5

value6

What I want is:

value1
value2

value3
value4

value5
value6

Upvotes: 0

Views: 59

Answers (3)

Chris
Chris

Reputation: 41

For the record, here is my edited version of divyenduz function:

function array_implode_with_value($array){
  $return = '';
  $num=0;
  foreach ($array as $value){
    $num+=1;
    $return .= $value . PHP_EOL;
    if($num%2==0)
      $return .= PHP_EOL;
    }
  return $return;
}

Many thanks all, you have been very helpful!

Upvotes: 2

Cheery
Cheery

Reputation: 16214

But, at first, please fix your array as it is incorrect - it has repeating keys/indexes.

$my = array(
      "type1"=>"car",    "brand1"=>"Citroen",
      "type2"=>"tablet", "brand2"=>"Asus",
      "type3"=>"cheese", "brand3"=>"Gouda"
);   

$my = array_chunk($my, 2);
foreach($my as $m)
  echo implode(PHP_EOL, $m) . PHP_EOL . PHP_EOL;

The correct one (or the best representation of data) will look like

$my = array(
     array("type" => "car", "brand" => "Citroen"),
     array("type" => "tablet", "brand" => "Asus"),
     array("type" => "cheese", "brand" => "Gouda")
);

foreach($my as $m)
  echo $m['type'] . PHP_EOL . $m['brand'] . PHP_EOL . PHP_EOL;

Upvotes: 2

divyenduz
divyenduz

Reputation: 2027

You can maintain a variable (Counter) and add PHP_EOL to the $return variable whenever your counter is even.

function array_implode_with_value($array){
  $return = '';
  $num=0;
  foreach ($array as $value){
    $num+=1;
    $return .= $value;
    if($num%2==0)
        $return .= PHP_EOL . PHP_EOL;
  }
  return $return;
}

I hope I got this one solved.

Upvotes: 1

Related Questions