k4h
k4h

Reputation: 117

how to display array properly

I have following array:

array(6) {
  [0]=>
  string(4) "XXX1"
  [1]=>
  int(16)
  [2]=>
  string(4) "YYY1"
  [3]=>
  string(4) "XXX2"
  [4]=>
  int(632)
  [5]=>
  string(4) "YYY2"
}

I would like to have an output like this:

First XXX - First int() - First YYY\n

Second XXX - Second int() - Second YYY\n

How to achieve this using while, for or foreach ?

Thanks.

Upvotes: 1

Views: 77

Answers (2)

Starson Hochschild
Starson Hochschild

Reputation: 754

Like Pe de Leao, I'm not 100% sure I understand the output you desire, but here are two candidates:

Does not check for a full "set" of 3:

<?php
$flat = array(
    "XXX1",
    16,
    "YYY1",
    "XXX2",
    632,
    "YYY2"
);

for ($i = 0; $i < count($flat); $i += 3)
    echo "{$flat[$i]} - {$flat[$i + 1]} - {$flat[$i + 2]}\n";
?>

Does check for a full "set" of 3:

<?php
$flat = array(
    "XXX1",
    16,
    "YYY1",
    "XXX2",
    632,
    "YYY2",
    "XXX3",
    932
);

for ($i = 0; $i < count($flat) && ($i + 3) < count($flat); $i += 3)
    echo "{$flat[$i]} - {$flat[$i + 1]} - {$flat[$i + 2]}\n";
?>

The examples are not fool-proof, for instance they make assumptions such as the array being numerically indexed with no holes, but I hope this is close enough to what you want.

Upvotes: 1

Expedito
Expedito

Reputation: 7805

I don't know exactly what kind of output you're looking for, but this puts it in paragraph tags:

$cnt = 0;
$out = '<p>';
foreach ($arr as $key => $value){
    $out .= $value.' - ';
    $cnt++;
    if ($cnt == 3){
        $cnt = 0;
        $out = substr($out, 0, -3).'</p><p>';
    }
}
$out = substr($out, 0, -3);

Upvotes: 1

Related Questions