Nathalie
Nathalie

Reputation: 113

PHP: Why are the first 3 array values printed over and over?

I am new to programming, trying to learn PHP and code separation between PHP and HTML.

I would like to replace certain words in an HTML-file ($replacehtml) with values from an array ($list). The HTML-file consists of one table row with 3 values to be replaced ($ip, $date, $browser). I want to print that same row several times (with new values from the array each time) until all of the values from the array has been printed. But my code seem to print the first 3 values over and over, and I'm not sure why. I'm sure I have missed something and would appreciate some help.

$list = array('ip1', 'date1', 'browser1','ip2','date2','browser2');

$n = 0;
   for ($i=0 ; $i < count($list)-1 ; $i++){

       if($n > count($list)-1){
           break;
       }
        $replacehtml = str_replace($ip, $list[$n], $replacehtml);
        $n++;
        $replacehtml = str_replace($date, $list[$n], $replacehtml);
        $n++;
        $replacehtml = str_replace($browser, $list[$n], $replacehtml);
        $n++;
        echo $replacehtml;
    }

I get the following output:

ip1 date1   browser1
ip1 date1   browser1

While it should have been:

ip1 date1   browser1
ip2 date2   browser2

Upvotes: 1

Views: 51

Answers (2)

Nigel Ren
Nigel Ren

Reputation: 57121

Apart from duplicating the looping, the main problem comes from overwriting the original string you are replacing into...

$replacehtml = str_replace($ip, $list[$n], $replacehtml);

so the second time it comes round the loop, $replacehtml has already had all of the values replaced.

Just use a different variable to put the value into and the subsequent replacements...

$newhtml = str_replace($ip, $list[$n], $replacehtml);

and then

$newhtml = str_replace($date, $list[$n], $newhtml);

etc. and finally

echo $newhtml;

Upvotes: 1

Run_Script
Run_Script

Reputation: 2548

Why do you define the variable $i but never use it? And then you replicate the function of a for loop by incrementing your variable $n instead of using the useful built-in function.

To achieve the output you want, I would use the following, much simpler, code:

$list = array('ip1', 'date1', 'browser1','ip2','date2','browser2');


for ($i = 0; $i < count($list); $i += 3){

  $replacehtml = str_replace($ip, $list[$i], $replacehtml);
  $replacehtml = str_replace($date, $list[$i + 1], $replacehtml);
  $replacehtml = str_replace($browser, $list[$i + 2], $replacehtml);

  echo $replacehtml;

}

This should achieve your expected output.

Upvotes: 1

Related Questions