Looking to calculate average of $data array. I need to first find the sum of the values in the array. Here's what I have but it doesn't seem to work.
$sum = 0;
foreach($data as $value) {
$sum = $sum+$value;
return $sum;
}
$count = count($data);
$average = $sum / $count;
echo "Average is $average <br />";
Try this:
$total = array_sum($data);
$average = $total / count($data);
Or, if you like one-liners:
$average = array_sum($data) / count($data);
remove the return
$sum = 0;
foreach($data as $value) {
$sum = $sum+$value;
}
$count = count($data);
$average = $sum / $count;
echo "Average is $average <br />";
The reason it's failing is that you shouldn't have the return statement. return is only used for returning from functions.
That said, you can just use array_sum() instead.
Related
I had a task to write program that gives 20 numbers from 9 to 99 using empty array and rand function which I did...but the second step is for me to calculate and get the average number.
With functions like array_sum I can get what I want, but the idea is not to use any of array functions, just arithmetic operators
$arrNums = array();
$sum = 0;
$intTotalNum = 20;
for($i = 0; $i < $intTotalNum; $i++) {
$intRand = rand(9, 99);
$arrNums[] = $intRand;
$sum = $sum + $arrNums;
$average = $sum / count($arrNums);
}
var_dump($arrNums);
echo "<br>";
echo $average;
Code gives me an error "Unsupported operand types"
This is how you can achieve it without using an array functions:
$arrNums = array();
$sum = 0;
$intTotalNum = 20;
for($i = 0; $i < $intTotalNum; $i++)
{
$intRand = rand(9, 99);
array_push($arrNums,$intRand);
$sum = $sum+$intRand;
}
echo '<pre>';
print_r($arrNums);
echo "<br>";
echo $sum;
//echo $average;
Just add your $sum to current $intRand and print it outside the loop.
The reason why I have used array_push functions so that you can print all the array elements outside for loop and check and verify how many numbers generated. If you don't want to print an array then it is no need, you can comment or remove it.
Just put the $average out side the for loop
$arrNums = array();
$sum = 0;
$intTotalNum = 20;
for($i = 0; $i < $intTotalNum; $i++) {
$intRand = rand(9, 99);
$arrNums[] = $intRand;
$sum += $intRand;
}
$average = $sum / $intTotalNum;
var_dump($arrNums);
echo "<br>";
echo $average;
You are trying add a integer with an array that's why the error "Unsupported operand types" . you can get the average more easily like this
$sum = 0;
$intTotalNum = 20;
$arrNums = array();
for($i = 0; $i < $intTotalNum; $i++) {
$arrNums[] = rand(9, 99);
$sum = $sum + $arrNums[$i];
}
$average = $sum / $intTotalNum;
var_dump($arrNums);
echo "<br>";
echo $average;
I was messing around with PHP and I figured out how to list 5 random integers between 1 and 100 using a for loop:
for($row = 1; $row <= 5; $row++) {
echo rand(1,100) . "<br>";
}
I know that I can get the sum of random numbers by doing the following:
$sum = 0;
for($row = 1; $row <= 5; $row++) {
$sum += rand (1,100) . "<br>";
}
echo $sum;
But now I don't know how I can echo the rands to be seen as well.
I want to be able to somehow combine the first piece of code and the second to get the list of random integers and their sum.
If you're planning to reuse the data, store them in a variable.
You should be looking into array's here:
for($sum = 0, $row = 1; $row <= 5; $row++) {
$num = rand (1,100);
$nums[] = $num;
$sum += $num;
}
echo "the total sum is: '$sum' with the values of: '" . implode(', ', $nums) . "'.";
Or just loop through it:
foreach($nums as $value){
echo $value, '<br>';
}
This is what I ended up using, and it worked! Thanks!
<?php
for($row = 1; $row <= 5; $row++) {
$value = rand (1,100);
echo $value . "<br>";
$sum += $value;
}
echo $sum;
?>
Let's say I have this array
$number = [2,1,4,3,6,2];
First pair the elements on an array by two's and find their difference
so this is the output in the first requirement
$diff[] = [1,1,4];
Second sum all the difference
this is the final output
$sum[] = [6];
Conditions:
the array size is always even
the first element in a pair is always greater than the second one, so their is no negative difference
What I've done so far is just counting the size of an array then after that I don't know how to pair them by two's. T_T
Is this possible in php? Is there a built in function to do it?
One line:
$number = [2,1,4,3,6,2];
$total = array_sum(array_map(function ($array) {
return current($array) - next($array);
}, array_chunk($number, 2)));
echo $total;
This should work fine:
<?
$number = array(2,1,4,3,6,2);
for($i=0;$i<count($number); $i+=2){
$dif[] = $number[$i] - $number[$i+1];
}
print_r($dif);
$sum = 0;
foreach ($dif as $item){
$sum += $item;
}
echo 'SUM = '.$sum;
?>
Working CODE
If you want all the different stages kept,
$numbers = [2,1,4,3,6,2];
$diff = [];
for($i=0,$c=count($numbers);$i<$c;$i+=2)
{
$diff[] = $numbers[$i]-$numbers[$i+1];
}
$sum = array_sum($diff);
Else, to just get the total and bypass the diff array:
$numbers = [2,1,4,3,6,2];
$total = 0;
for($i=0,$c=count($numbers);$i<$c;$i+=2)
{
$total += $numbers[$i]-$numbers[$i+1];
}
I have got this far it gives the required solution.
$arr = array(2,1,4,3,6,2);
$temp = 0;
$diff = array();
foreach ($arr as $key => $value) {
if($key % 2 == 0) {
$temp = $value;
}
else {
$diff[] = $temp - $value;
}
}
print_R($diff);
print 'Total :' . array_sum($diff);
Note : Please update if any one knows any pre-defined function than can sorten this code.
Please check and see if this works for you.
<?php
$sum=0;
$number = array(2,1,4,3,6,2);
for ($i=0;$i<=count($number);$i++) {
if ($i%2 == 1 ) {
$sum = $sum + $number[$i-1] - $number[$i];
}
}
print $sum;
?>
Well with your conditions in mind I came to the following
$number = [2,1,4,3,6,2];
$total = 0;
for($i = 0; $i < count($number); $i+=2) {
$total += $number[$i] - $number[$i + 1];
}
Try this one:
$number = array(2,1,4,3,6,2);
$diff = array();
$v3 = 0;
$i=1;
foreach($number as $val){
if ($i % 2 !== 0) {
$v1 = $val;
}
if ($i % 2 === 0) {
$v2 = $val;
$diff[] = $v1-$v2;
$v3+= $v1-$v2;
}
$i++;
}
print $v3;//total value
print_r($diff); //diff value array
I've got field in my database which contain strings like 21;48;33;22;31. Then I'd like to convert it to mathematical calculation 21+48+33+22+31.
$points = "21;48;33;22;31";
$points = str_replace(";","+",$points );
$points = preg_replace('/[^0-9\+\-\*\/\s]+/', '', $points);
echo $points;
But that simply does not work. I've got the same string "21+48+33+22+31" instead of the sum.
$points = "21;48;33;22;31";
$points = explode(';',$points );
$points = array_sum($points);
echo $points;
$points = "21;48;33;22;31";
$arr = explode(";", $points);
$points = 0;
foreach($arr as $key => $rows){
$points += $rows[$key];
}
echo $points;
Try above code it will give you proper result.
or you can try it also:
$points = "21;48;33;22;31";
$arr = explode(";", $points);
echo $points = array_sum($arr);
The easiest way is to explode the string.
Then you can iterate with foreach over the resulting array and calculate them.
$points = "21;48;33;22;31";
$points = explode(";", $points);
$calc = 0;
forearch($points as $point) {
$calc += $point;
}
Or your can use array_sum:
$points = "21;48;33;22;31";
$points = explode(";", $points);
$calc = array_sum($points);
Something like that. Perhaps there are some shorter ways.
$string = "21;48;33;22;31";
$string = explode(";" , "21;48;33;22;31");
$point = 0;
foreach($string as $num)
{ // by using (int) you can convert string to int.
$point = (int)$num + $point;
}
print($point);
// output
155
explode it then loop for sum...
<?php
$total = 0; // for getting the total
$points = "21;48;33;22;31";
$points = explode(';',$points);
for($i=0;$i<count($points);$i++){
$total+= $points[$i];
}
echo $total;
?>
<?php
eval('$sum = ' . str_replace(';','+','21;48;33;22;31').';');
echo $sum;
<?php
$txtfield = $_POST['number1'];
$arr = explode(' ',trim($txtfield));
$operator = $arr[0];
$count=count($arr);
$sum = array_sum($arr);
echo "Sum of the number:".$sum. "<br>";
$prod=1;
for ($i=1; $i<$count; $i++){
$prod = $prod * $arr[$i];}
echo "Product of the numbers:".$prod."<br>";
$diff=$arr[1];
for ($i=1; $i<$count; $i++){
$diff= $diff - $arr[$i+1];
}
echo "Difference of the numbers:".$diff."<br>";
$div=$arr[1];
foreach ($i=1; $i<$count; $i++){
$div=$div / $arr[$i];
}
echo "Qoutient of the numbers:". $div. "<br>";
?>
This line of code doesn't seem to work properly. When I entered 10 & 5 the output is:
Sum of the number:15
Product of the numbers:50
Difference of the numbers:5
Qoutient of the numbers:0.2
Assuming that by I entered 10 & 5 you mean that $arr looks like this:
$arr = array(
1 => 10,
2 => 5
);
...then 0.2 is the expected result of the quotient. This is what your code does:
$div = 10;
$div = 10 / 10; // 1
$div = 1 / 5; // 0.2
I think that you meant to initialise $i at 2. This will give your expected output. But a better approach would be this:
$arr = array(
10,
5
);
// Make a copy of $arr before this if you need the original data intact
$quotient = array_shift($arr);
foreach ($arr as $val) {
$quotient /= $val;
}
Now the element indexes are irrelevant, only the element order is significant.
EDIT
Here is how I would write your newly posted full code:
// Split on any number of whitespace characters to avoid bad user input
$arr = preg_split('/\s+/', $_POST['number1']);
// Remove the first element of the array so it doesn't interfere with calculations
$operator = array_shift($arr);
// This is fine
$sum = array_sum($arr);
// Product has a function of it's own
$prod = array_product($arr);
// Difference and quotient can be done in one loop
$diff = $quot = array_shift($arr);
foreach ($arr as $val) {
$diff -= $val;
$quot \= $val;
}
// Echo the results
echo "Sum of the number:".$sum."<br>";
echo "Product of the numbers:".$prod."<br>";
echo "Difference of the numbers:".$diff."<br>";
echo "Qoutient of the numbers:".$quot."<br>";
I've reformatted your program and added static values so that it will execute standalone.
<?php
$arr = array(10, 5);
$count = count($arr);
$sum = array_sum($arr);
echo 'Sum of the number: '.$sum."<br>\n";
$prod = 1;
for($i = 0; $i < $count; $i++)
{
$prod *= $arr[$i];
}
echo 'Product of the numbers: '.$prod."<br>\n";
$diff = $arr[0];
for($i = 1; $i < $count; $i++)
{
$diff -= $arr[$i];
}
echo 'Difference of the numbers: '.$diff."<br>\n";
$div = $arr[0];
for($i = 1; $i < $count; $i++)
{
$div /= $arr[$i];
}
echo 'Quotient of the numbers: '.$div."<br>\n";
?>
The output of this program is:
Sum of the number: 15
Product of the numbers: 50
Difference of the numbers: 5
Quotient of the numbers: 2