Reading 2 times an array

0

Well I have the following array:

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

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

foreach ($teste as $c) {

    echo $c;

}

The result is: 1234

I need to write the result 2 times and following the order, like this: 11223344

Does anyone know how to do this using just foreach ?

The code that is inside foreach is large and I do not want to repeat it, I want to find some way to do this in%     

asked by anonymous 14.11.2018 / 13:06

2 answers

4

I would recommend you refactor your code. If it is reusable, it could very well be defined in a function. In this case, it would suffice to do:

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

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

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

So, you just have to do it:

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

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

See working at Repl.it

    
14.11.2018 / 13:30
1

Alternatively, you can control using another repeat structure

foreach ($teste as $c) {
  for (int $i=0; $i<2; $i++){
    echo $c;
  }
}
    
14.11.2018 / 13:20