skip to Main Content

How to count all data item array in laravel, please help me!. Thank you so much!

enter image description here

Output: 8

3

Answers


  1. reduce()

    The reduce method reduces the collection to a single value, passing
    the result of each iteration into the subsequent iteration:

    $count = collect([
        (object)["views_back" => 3],
        (object)["views_back" => 5]
    ])->reduce(function ($carry, $item) {
        return $carry + $item->views_back;
    });
    
    var_export($count); // 8
    

    Addendum

    Alternatively, using native/vanilla PHP:

    $count = array_sum(array_column([
        (object)["views_back" => 3],
        (object)["views_back" => 5]
    ], "views_back"));
    
    var_export($count); // 8
    
    Login or Signup to reply.
  2. When working with arrays in Laravel, it can be helpful to convert them to a Collection which provides some helper methods for arrays.

    If all you want is the number of elements in the array use count.

    If you want the sum of the views_back elements, use reduce.

    $array = [
        [
            'views_back' => 3,
        ],
        [
            'views_back' => 5,
        ]
    ];
    
    $count = collect($array)->count();
    
    $sum = collect($array)->reduce(function ($carry, $element) {
        return $carry + $element['views_back'];
    });
    
    dd($count, $sum);
    

    In the above $count is 2 and $sum is 8.

    If your original data is json (as you’ve used a json tag), you will need to convet the data to an array first:

    $array = json_decode($json, true);
    
    Login or Signup to reply.
  3. You can use laravel collection method sum() method to write smaller code and make it easier to read.

    $data = [
        (object)["views_back" => 3],
        (object)["views_back" => 5]
    ];
    
    collect($data)->sum('views_back');
    

    Converting array to collection can be CPU costly depending on the size of the input array. In that case @steven7mwesigwa vanilla PHP answer would be the best solution.

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