0

I have an array that looks like follows:

$table_arr[] = {
               [0][['arg1'] => data1, ['arg2'] => data2, ['arg3'] => data, ['line_count'] => 2],
               [1][['arg1'] => data1_1, ['arg2'] => data2_1, ['arg3'] => data3_, ['line_count'] => 4]
               };

I want to add a line_count value in the array(in above array 2 + 4 = 6)

so i can do this using php foreach. Is there any function for below logic (without using a loop)?

$val = 0;               
foreach($table_arr as key => value){
   if(key == 'line_count'){
      $val = $val + value;
   }
}  
1
  • I don't think there is a native function in PHP, it's really specific functionality. Commented Feb 20, 2014 at 11:19

3 Answers 3

2

If your php version >=5.5, then try using array_columns with array_sum, but still there will be internal looping

echo array_sum(array_column($table_arr,'line_count'));

See demo here

Sign up to request clarification or add additional context in comments.

Comments

1

Can do better like

foreach($table_arr as $arr){       
      $val += $arr['line_count'];       
}  
echo $val;

1 Comment

Thats same as my solution. Is there any solution with out using foreach?
0

You schould look in to phps array_sum https://www.php.net/array_sum

this functions sums all values in an array returning the total value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.