1

in a project, I define a text-block like e.g.:

$test = '<div>Name'.$i.':&nbsp;<input type="text" name="name'.$i.'" value="'.$_POST['name'.$i].'" /></div>';

The text-block is then used within a for-loop like:

$_POST['name1'] = 'Max';

for($i=0;$i<3;$i++){
  $test = '<div>Name'.$i.':&nbsp;<input type="text" name="name'.$i.'" value="'.$_POST['name'.$i].'" /></div>';
  echo $test;
  }  

This produces the desired result:

<div>Name0: <input type="text" name="name0" value=""></div>
<div>Name1: <input type="text" name="name1" value="Max"></div>
<div>Name2: <input type="text" name="name2" value=""></div>

Now, I would like to get the text-block $test from a database and use it within the loop but I cannot figure out how to modify the variables $i to work.

Actually, it is like:

$_POST['name1'] = 'Max';
$string = '<div>Name'.$i.':&nbsp;<input type="text" name="name'.$i.'" value="'.$_POST['name'.$i].'" /></div>';

for($i=0;$i<3;$i++){
  $test = $string;
  echo $test;
  }   

Can anybody give me a hint on how to achieve this?

1
  • Well, for now I have to make sure that the indexes are properly set - if I find some time I will give your approach a try... Commented Sep 16, 2016 at 14:50

1 Answer 1

1

If your content of $string is something like a template for HTML which can't generate on the go, I would save it in the database like this with usage of some kind of placeholders which you will later replace in the for loop: '<div>Name%i%:&nbsp;<input type="text" name="name%i%" value="%name%" /></div>'

Then you do

$string = $thatDbStoredTemplate; 
for($i=0;$i<3;$i++){
    $test = str_replace(array("%i%", "%name%"), array($i, $_POST["name". $i]), $string);  
    echo $test;
}   

Btw, you should also check if $_POST["name". $i] exists with isset, otherwise you will get Notice level warning.

Sign up to request clarification or add additional context in comments.

1 Comment

Just tested it with the real code (much more complicated and bigger than in the example!) - works like a charm. As always, I was thinking more complicated then necessary... Thanks a lot, Jan!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.