skip to Main Content

I am writing html in PHP file, I am trying to output $count value in html but using for each loop later, How can i do it,

Code –

<div>Total class: <span>$count</span>
<div>Total student: <span>237</span>


<?php
foreach($cursor as $row){
$count = 0;
    foreach($row->class as $item){
                                                   
      $count+= count($row->class);

   }
 }
?> 

3

Answers


  1. You cannot use the variable first and the initialize later in php. For the same effect efficiently you can do something like.

    <div>Total class: <span><?php echo count($row->newsSources); ?></span>
    <div>Total student: <span>237</span>
    //rest of the code
    
    Login or Signup to reply.
  2. It is still not very clear what you are asking, but I think you want to render your html within the first loop, after the nested loop compleats. You can break the php code block after the nested loop ?> <?php or use echo.

    <?php
        foreach($cursor as $row) {
            $count = 0;
            foreach($row->class as $item) {
                $count+= count($row->class);
            }
    
            ?>
                <div>Total class: <span><?php echo $count; ?></span>
                <div>Total student: <span>237</span>
            <?php
        }
    ?> 
    
    Login or Signup to reply.
  3. You can change your HTML code like this:

    <div>Total class: <span id="count">$count</span>
    <div>Total student: <span>237</span>
    

    and then create JavaScript code like this to set the value.

    Edit: JavaScript code by PHP

    document.getElementById("count").innerHTML = variable;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search