0

I am trying to make a div ID have a unique name by using a variable to iterate through the number of times it gets looped. For some reason my $k variable doesn't seem to be advancing. Here is the code:

<?php foreach($files as $media)
                { 
                    $k = 0;
                    ?>
                    <h3><?php echo $output[$j] ?></h3>
                    <div id='mediaspace<?php echo $k ?>'>This text will be replaced</div>

                    <script type='text/javascript'>
                      ...
                      so.write('mediaspace<?php echo $k ?>');
                    </script>
                <?php 
                $k = $k+1;
                } ?>

My HTML output just gives me a 0 for $k every time the loop is run:

<div id='mediaspace0'>This text will be replaced</div>


                    <script type='text/javascript'>
                     ...                  so.write('mediaspace0');
                    </script>
                                        <h3>Rattletree Marimba Day</h3>
                    <div id='mediaspace0'>This text will be replaced</div>

                    <script type='text/javascript'>
                      ...                 so.write('mediaspace0');
                    </script>

Any help greatly appreciated!

3 Answers 3

10

Of course:

$k = 0;

Reset the variable before the loop.

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

Comments

2
$k = 0;

at the start of the loop resets your $k to 0 at the start of each iteration.

Move it outside the loop:

<?php 
$k = 0;
foreach($files as $media)
{ 
...

Comments

1

You are setting $k to 0 at the begining of your foreach.

Set it outside.

$k = 0;
foreach($files as $media) {
...

Comments

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.