Division with Arrays - php

<?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

Related

How I can get average number from array without using array_sum or any other function?

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;

How to create second array and display numbers that are greater than average number of first array?

I want to make second array that gives all numbers using rand function that are greater than average number of first array.
I've created new array and I've tried with if statement to display all numbers greater than average number, and to put those values into a new empty array
$arrNums = array();
$arrNewNums = array();
$intSum = 0;
$intTotalNum = 20;
for($i = 0; $i < $intTotalNum; $i++)
{
$intRand = rand(9, 99);
$arrNums[] = $intRand;
$intSum = $intSum + $arrNums[$i];
$averageNum = $intSum / count($arrNums);
foreach($arrNums as $key => $value)
{
if($value > $averageNum)
{
$arrNewNums[] = rand();
}
}
}
echo '<pre>';
print_r($arrNums);
echo "<br>";
echo "Average number from array is " . $averageNum;
echo "<br>";
print_r($arrNewNums);
I would like to get the output of 20 numbers greater than average number, for example 56.4, but instead of that I'm getting 100 numbers and they are all for example 864165243, 738017258 and so on and so on...
This is the correct code for your task:
$arrNums = array();
$arrNewNums = array();
$intSum = 0;
$intTotalNum = 20;
for($i = 0; $i < $intTotalNum; $i++)
{
$intRand = rand(9, 99);
$arrNums[] = $intRand;
$intSum += $intRand;
}
// count average value AFTER you have all items in array
// $averageNum = array_sum($arrNums) / count($arrNums);
// Without `array_sum`:
$averageNum = $intSum / count($arrNums);
// check values of array AFTER you have all items in array
foreach($arrNums as $value) {
if($value > $averageNum) {
// add `$value` to `$arrNewNums`, not some random variable.
$arrNewNums[] = $value;
}
}
echo '<pre>';
print_r($arrNums);
echo "<br>";
echo "Average number from array is " . $averageNum;
echo "<br>";
print_r($arrNewNums);

get a set of values from an array

i have a set of arrays:
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
what i want to do is to get a set of $data array from each number of $nums array,
the output must be:
output:
2=11,22
3=33,44,55
1=66
what i tried so far is to slice the array and remove the sliced values from an array but i didn't get the correct output.
for ($i=0; $i < count($nums); $i++) {
$a = array_slice($data,0,$nums[$i]);
for ($x=0; $x < $nums[$i]; $x++) {
unset($data[0]);
}
}
Another alternative is to use another flavor array_splice, it basically takes the array based on the offset that you inputted. It already takes care of the unsetting part since it already removes the portion that you selected.
$out = array();
foreach ($nums as $n) {
$remove = array_splice($data, 0, $n);
$out[] = $remove;
echo $n . '=' . implode(',', $remove), "\n";
}
// since nums has 2, 3, 1, what it does is, each iteration, take 2, take 3, take 1
Sample Output
Also you could do an alternative and have no function usage at all. You'd need another loop though, just save / record the last index so that you know where to start the next num extraction:
$last = 0; // recorder
$cnt = count($data);
for ($i = 0; $i < count($nums); $i++) {
$n = $nums[$i];
echo $n . '=';
for ($h = 0; $h < $n; $h++) {
echo $data[$last] . ', ';
$last++;
}
echo "\n";
}
You can array_shift to remove the first element.
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
foreach( $nums as $num ){
$t = array();
for ( $x = $num; $x>0; $x-- ) $t[] = array_shift($data);
echo $num . " = " . implode(",",$t) . "<br />";
}
This will result to:
2 = 11,22
3 = 33,44,55
1 = 66
This is the easiest and the simplest way,
<?php
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
$startingPoint = 0;
echo "output:"."\n";
foreach($nums as $num){
$sliced_array = array_slice($data, $startingPoint, $num);
$startingPoint = $num;
echo $num."=".implode(",", $sliced_array)."\n";
}
?>

Why is the answer of $sum 6?

<?php
$numbers = array(1,2,3,4);
$total = count($numbers);
$sum = 0;
$output = "";
$i = 0;
foreach($numbers as $number) {
$i = $i + 1;
if ($i < $total) {
$sum = $sum + $number;
}
}
echo $sum;
?>
I'm going through PHP on TeamTreehouse.com, whilst learning php this was one of the quiz question, the answer is 6. I don't know why the answer is 6, can someone explain?
The variable $i is initialized by 0 (zero).
Before the condition if ($i < $total) is tested $i is incremented by 1. So even the first time it equals 1.
In the third pass $i equals 3, and in the fourth pass it equals 4 which is NOT < $total.
Therefore only 3 of the 4 elements of $numbers are summed up: 1 + 2 + 3, which equals 6.
See the comments in the code below:
<?php
$numbers = array(1,2,3,4);
$total = count($numbers); // Gives 4
$sum = 0;
$output = "";
$i = 0; // $i = 0
foreach($numbers as $number) {
$i = $i + 1; // $i = 1, even at the first time
// after 3 passes $i is equal to $total (=4)
if ($i < $total) { // So, only 3 of the 4 elements of $number are honored
$sum = $sum + $number;
}
}
echo $sum; // Thus $sum = 1 + 2 + 3 = 6
// The last element (=4) is never summed up
?>
This would sum up all 4 elements, giving 10 as the result:
foreach($numbers as $number) {
if ($i < $total) {
$sum = $sum + $number;
}
$i = $i + 1;
}
<?php
$numbers = array(1,2,3,4);
$total = count($numbers); #value of $total is 4 here
$sum = 0;
$output = ""; #intital empty
$i = 0;
foreach($numbers as $number) {
$i = $i + 1;
if ($i < $total) {
$sum = $sum + $number;
}
}
echo $sum;
?>
You increment the $i by 1 so it becomes 1 which is smaller than $total(which is 4). Your program will add till $i become 4. It just add first three number in your array.
1+2+3=6.
That's why you are getting 6.
I hope you get it. :)
The condition limits the iterations. When $i is 4 it is no longer less than $total and so the last number doesn't get added.

Pair the elements in an array by two's then find the difference and 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

Categories