Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Increment the variable each time you run the function

Tags:

php

class

laravel

I have a function in my Helper Class that should increment the variable each time the function is called.

Here is my code:

<?php

class Helper 
{

  public static $count;

  public static function voiceHelper($questionArray)
  {
    $count = self::$count;
    // $count = 0;
    if(count($questionArray) >= $count)
    {
        $count++;
        return $count;

    } else if($count > count($questionArray))
    {
        $count == 0;
        return $count;
    }
   }

}

I expect that the count variable will increment each time the function is called but it still remains 1.

like image 772
The Ninja Avatar asked Feb 06 '26 03:02

The Ninja


1 Answers

Try:

class Helper 
{

  public static $count;

  public static function voiceHelper($questionArray)
  {

    // $count = 0;
    if(count($questionArray) >= $count)
    {
        self::$count++;
        return self::$count;

    } else if($count > count($questionArray))
    {
        self::$count = 0;
        return self::$count;
    }
   }

}

Looks like you are just incrementing the $count without adding it to the static count property. Therefore you will always get 1. Instead actually increment the static count property.

like image 77
Joseph_J Avatar answered Feb 07 '26 16:02

Joseph_J



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!