Reading an array 2 times

Asked

Viewed 66 times

0

Well I have the following array:

$teste = array(1,2,3,4);

When I want to write it on the screen I do so?

foreach ($teste as $c) {

    echo $c;

}

The result is: 1234

I need to write the result twice and follow the order, like this: 11223344

Does anyone know how to do this using just one foreach?

Note: The code inside the foreach and big and I don’t want to repeat it, I want to find some way to do it in foreach

  • 3

    It’s not enough to do echo $c, $c? https://repl.it/@acwoss/EvenOutstandingRuby

  • Not da, that was a short example, the code is big and I don’t want to have to repeat it, I have to do it in foreach

  • 2

    Then your example does not reproduce the real problem, leaving your question insufficiently clear. Please edit the question by elaborating a [mcve].

  • I just edited her

  • 1

    can’t have a loop within the foreach? guy while ($contador < 2)??

  • Yeah, good idea.

  • 3

    There is also always the possibility for you to refactor your code and put what is reusable into functions.

  • Can you provide the foreach and their code inside the Pastebin ? So the staff can get an idea of what you’re talking about

Show 3 more comments

2 answers

4


I would recommend you refactor your code. If it is reusable, it could very well be set in a function. In that case, just do:

foreach ($teste as $c) {
    echo foo($c), foo($c);
}

But if you want to get around it, you can go through the array through a generator:

function doubleForeach($arr) {
    foreach($arr as $item) {
        yield $item;
        yield $item;
    }
}

So just do it:

$teste = array(1,2,3,4);
$iterator = doubleForeach($teste);

foreach ($iterator as $c) {
    echo $c;
}

See working on Repl.it

  • Very good your solution

1

Alternatively, you can control using another repeat structure

foreach ($teste as $c) {
  for (int $i=0; $i<2; $i++){
    echo $c;
  }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.