1

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.

0

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.