Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Concatante PHP variables inside loop by a "Concatenating Assignment Operator", and Echo each output loop separately

With the "Concatenating Assignment Operator" I assigned in the loop two variables. I need to get each loop result separately. The problem is that I don’t know why each next loop result is copied to each next loop result.

<!DOCTYPE html>
<html>
    <body>
        <?php 
            $output = "";
            $number = "";
            $start = 0;
            $end = 5;

            $array = array();

            while($start <= $end) {
                $number = $start+=1;
                $output .= "1";
                $output .= "2";

                $array [] = $output;
            }
            echo json_encode(array (
                'output'=>$array,
            ));
        ?>
    </body>
</html>

Using this code, I get the output:

{"output":["12","1212","121212","12121212","1212121212","121212121212"]} 

I’m working on making the output look like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{"output":["12","12","12","12","12","12"]} 

>Solution :

You are always concatenating values to the $output, you never clear it, so the numbers are just continually added. All you need to do is change the first $output .= "1"; in to a $output = "1"; and that will have the effect of resetting $output to the one character ready to be concatenated with the second.

while($start <= $end) {
    $number = $start+=1;

    $output = "1";      // changed here
    $output .= "2";

    $array [] = $output;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading