skip to Main Content

I have a trouble from my controller. When i want to count the array from another function in controller is get a error cannot to count

I get this error

Call to a member function get() on array

This my controller :

Function A
public function detailFees(){
$dataArray = array(
    'datapayment' => $datapayment,
    'countafter' => $countafter,
    'countbefore' => $countbefore
  );
}

Function B
public function data(){
$data = count($this->detailFees($market)->get(datapayment))
}

I want to count just array data in datapayment with result in number

Thanks for help!

3

Answers


  1. You can’t use get() on an array because it is not a valid operation, and your detailFees() method does not accept any arguments because you did not define a parameter in the method.

    To count the array, you can do this:

    // Function B
    public function data() {
        $dataArray = $this->detailFees();
        $datapayment = $dataArray['datapayment'];
        $dataCount = count($datapayment);
    
    
        return $dataCount;
    }
    
    Login or Signup to reply.
  2. Inorder to make use of the get() method, convert the array as a collection using the collect() helper method.

    Function A:

    public function detailFees($key)
    {
        $dataArray = collect(
            'datapayment' => $datapayment,
            'countafter' => $countafter,
            'countbefore' => $countbefore
        );
    
        $item = $dataArray->get($key);
    
        if (
            is_null($item)
            || ! is_array($item)
        ) {
            return 0;
        }
    
        return count($item);
    }
    

    Function B:

    public function data()
    {
        $data = $this->detailFees('datapayment');
    }
    
    Login or Signup to reply.
  3. Actually, there are few ways to achieve your goal. The minimum cost is just returning $dataArray in function A

    public function detailFees( $market ){
        // .... your other codes
        $dataArray = array(
            'datapayment' => $datapayment,
            'countafter'  => $countafter,
            'countbefore' => $countbefore
        );
        return $dataArray; // add this line
    }
    

    and then consume the returned array from function A to function B:

    public function data(){
        $data = count($this->detailFees($market)['datapayment']); // change this line
    }
    

    simple without many changes.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search