How to count all data item array in laravel, please help me!. Thank you so much!
Output: 8
3
reduce()
The reduce method reduces the collection to a single value, passing the result of each iteration into the subsequent iteration:
reduce
$count = collect([ (object)["views_back" => 3], (object)["views_back" => 5] ])->reduce(function ($carry, $item) { return $carry + $item->views_back; }); var_export($count); // 8
Alternatively, using native/vanilla PHP:
$count = array_sum(array_column([ (object)["views_back" => 3], (object)["views_back" => 5] ], "views_back")); var_export($count); // 8
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.
count
If you want the sum of the views_back elements, use reduce.
views_back
$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.
$count
2
$sum
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:
json
$array = json_decode($json, true);
You can use laravel collection method sum() method to write smaller code and make it easier to read.
sum()
$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.
Click here to cancel reply.
3
Answers
reduce()
Addendum
Alternatively, using native/vanilla PHP:
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, usereduce
.In the above
$count
is2
and$sum
is8
.If your original data is
json
(as you’ve used ajson
tag), you will need to convet the data to an array first:You can use laravel collection method
sum()
method to write smaller code and make it easier to read.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.