Search code examples
phpfunction-declaration

How Can I use a function multiple times on the same page?


Say this piece of code:

 <?php while($user=mysqli_fetch_array($resultuser)){ ?>
 <?php 

   function my_function($variable) {
      //do something here...
    }
 ?>
<?php };?>

This will obviously return this error

Cannot redeclare my_function() previously declared

So what if someone needs to use the same function multiple times across the same page? Is there a way to generate random function() names? Any idea how to get around this? Thanks.

EDIT WITH ACTUAL CODE

    <?php while($deposit26=mysqli_fetch_array($resultdeposit26)){ ?>
<td  data-th="Hours">
    <?php 
        $week1hours = $deposit26['hours_worked'];
        $week2hours = $deposit26['hours_worked_wk2'];
        function time_to_decimal($time) {
        $timeArr = explode(':', $time);
        $decTime = ($timeArr[0] + ($timeArr[1]/60) + ($timeArr[2]/3600));
        return $decTime;
        }
        $groupd26hours = time_to_decimal($week1hours) + time_to_decimal($week2hours);
        echo round($groupd26hours, 2);
     ?>
</td>
  <?php };?>

Solution

  • <?php 
    // Earlier in the file or included with include or require
    function time_to_decimal($time) {
            $timeArr = explode(':', $time);
            $decTime = ($timeArr[0] + ($timeArr[1]/60) + ($timeArr[2]/3600));
            return $decTime;
    } ?>
    

    ...

        <?php while($deposit26=mysqli_fetch_array($resultdeposit26)) : ?>
        <td  data-th="Hours">
        <?php 
            $week1hours = $deposit26['hours_worked'];
            $week2hours = $deposit26['hours_worked_wk2'];
            $groupd26hours = time_to_decimal($week1hours) +   time_to_decimal($week2hours);
            echo round($groupd26hours, 2); ?>
        </td>
        <?php endwhile ?>