Combine all array values

I have a loop like below:

foreach ($header as $i) {
    $i += $i;
}

I am trying to load a variable ($ i), and then outside of this echo loop, such a variable as shown below:

echo $i;

However, it always returns 0;

Is it possible to return to it the value that it created in the loop?

+3
source share
3 answers
foreach ($header as $i) {
    $i += $i;
}

There are many problems in the above code. Other answers solve them, but without explanation, so you may find this helpful. For the purposes of this answer, I assume that it $headercontains array('a', 'b', 'c'), and that you intend to combine the values.

-, numeric add += .=. $i 0: $header , +=, , , 0.

-, .=, $i , . :

$i = 'a';
$i .= $i' // aa

:

 $i = 'b';
 $i .= $i; // bb

. . , , $i , .

, , , (+=, .=, *= ..)). E_NOTICE error_reporting php.ini, .

+3

implode() .

$all = implode('', $header);

http://php.net/implode

+11

$i reassigned each time the cycle repeats.

create a variable outside the loop, add to it during the loop and again echo outside it.

$outside_var = 0;

foreach ($header as $i) {
    $outside_var += $i;
}

echo $outside_var;
+6
source

Source: https://habr.com/ru/post/1788008/


All Articles