php - how to display array properly

613

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.

532

Answer

Solution:

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);
803

Answer

Solution:

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.

People are also looking for solutions to the problem: content management system - How to make your custom php CMS work only on a certain domain for a certain time?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.