0

i have a veriable named (num) which is used for increments changes names of ids by 1 num+1 but in my foreachloop i cant access it .

i tried declaring it before the loop still doesnot work

<?php $num = 0; ?>
<?php foreach($listings as $list):?>
    <li>
        <div class="checkbox">
            <input type="checkbox" class="css-checkbox" value="<?php echo $list['title'];?>" id="visit<?php echo $num+1;?>" name="treatment<?php echo $num+1;?>">
            <label for="visit<?php echo $num+1;?>" class="css-label"><?php echo $list['title']?> <strong><?php echo $list['price'];?><span>&#163;</span></strong></label>
        </div>
    </li>
<?php endforeach;   ?>
</ul>
<hr>
<input type="hidden" value="<?php echo $num;?>" name="total"/>

i want the input ids to be incremented by 1 like treatment1,treatment2

2
  • Can't replicate the problem... 3v4l.org/40k5h Commented May 20, 2019 at 18:25
  • use ... as $num => $list and skip the outside declaration of $num Commented May 20, 2019 at 18:27

2 Answers 2

2

You should increment the $num variable by doing $num++; once inside the loop, then print it where you need it with <?php echo $num; ?> without using <?php echo $num+1; ?> - as doing so will only increment it as you echo it - not add one to each iteration.

<?php 
$num = 0;
foreach($listings as $list):
    $num++; // Increment $num for each iteration
    ?>
    <li>
        <div class="checkbox">
            <input type="checkbox" class="css-checkbox" value="<?php echo $list['title'];?>" id="visit<?php echo $num;?>" name="treatment<?php echo $num;?>">
            <label for="visit<?php echo $num;?>" class="css-label"><?php echo $list['title']?> <strong><?php echo $list['price'];?><span>&#163;</span></strong></label>
        </div>
    </li>
<?php endforeach; ?>

If your $listings is numeric indexed, you can use the key of each element in the array instead by doing

foreach($listings as $num=>$list):
    ?>
    <li>
        <div class="checkbox">
            <input type="checkbox" class="css-checkbox" value="<?php echo $list['title'];?>" id="visit<?php echo $num;?>" name="treatment<?php echo $num;?>">
            <label for="visit<?php echo $num;?>" class="css-label"><?php echo $list['title']?> <strong><?php echo $list['price'];?><span>&#163;</span></strong></label>
        </div>
    </li>
<?php endforeach; ?>
Sign up to request clarification or add additional context in comments.

Comments

1

The problem is you did not set the value of $num variable you just only print or echo it inside the html tags. You need to add or increment the $num variable inside the loop like this.

 <?php $num++; ?>

or

 <?php $num = $num+1; ?>

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.