0

I am about to give up. I knwo it is dman simple but... Here is what I have:

$stuff =     Array ( [0] => 1 ) Array ( [0] => 0.5 ) Array ( [0] => 0.5 ) 

I need a sum the values (so 1 + 0.5 + 0.5) to a string? what on Earth should I do? is there non-recursive way of doing so (like array_sum()) ? Thank you so much in advance.

7
  • To make sure I understand, you want to sum the values of each index correct? like $sum = $a[0] + $b[0] + $c[0]; Commented Oct 15, 2015 at 20:09
  • Also, you say 'to a string', this is not clear. Do you mean 2 as a result cast as a String? Commented Oct 15, 2015 at 20:19
  • $stuff is an array containing those three arrays in it. each of the arrays has a value (1 / 0.5 / 0.5) I need those to be summarized to return a string (not array) result Commented Oct 15, 2015 at 20:21
  • 1
    Well you could tell the database to SUM them for you Commented Oct 15, 2015 at 20:24
  • 1
    Or $sum = array_sum(array_column($stuff, 0)); Commented Oct 15, 2015 at 20:25

1 Answer 1

1

Not sure if this is what you're looking for. Simple answer, iterate over your array of arrays. When you have completed the calculation, re-cast the variable to String if you like.

<?php
$stuff = array(
    array(1),
    array(0.5),
    array(0.5)
);

$result = 0;
foreach($stuff as $i){
    $result += $i[0];
}

$stringResult = strval($result);
echo is_string($stringResult) . " : " . $stringResult;
// 1 : 2
?>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Lord Twisty! I do appreciate your help

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.