0

I'm tryng to learn PHP and I'm trying to do it by doing things the long way round. So I came across array_sum() and I was wondering if there is a way to calculate an array without using it.

for example

$my_array = array(10, 80, 30);

I've only got as far as this and I'm stumped. I have looked on google but I haven't found anything.

$implode = implode(",", $my_array );

$explode = explode(",", $implode);

foreach($explode as $test)
{


 }

4
  • Is there any specific reason that you want to do this? Commented Oct 15, 2019 at 7:56
  • $my_array would be the same as $explode. Can you tell us what are you trying to do? Commented Oct 15, 2019 at 7:57
  • just so that I learn and understand Commented Oct 15, 2019 at 7:57
  • Whenever a native function is there, use it. Because it is optimized. Don't invent the wheel, again. Commented Oct 15, 2019 at 8:00

1 Answer 1

2

I will always go for native functions as they are optimized as well as tested.[so basically i want to say that use array_sum()],

Apart from above, below is foreach() process to sum all values of a single-dimensional array[just for knowledge sake]

<?php


$result = 0; //create a variable with 0 value
foreach($explode as $test)
{
  $result += $test; //add array value to the newly created value

}

echo $result; //print final sum of all array values

Output:-https://3v4l.org/0qMJu

Note:- please read @Markus Zeller comment under question

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

2 Comments

That was it thank you so much.
@KittyKat glad to help you. please read my answer once again. I have added some note as well explanation too.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.