"Undefined variable: Profit $sum-$sub" - php

I am attempting to sum two arrays and subtract them from each other in PHP. Below is my attempt at it:
function total_price($totals)
{
$sum = 0;
$sub = 0;
foreach ($totals as $total)
{
$sum += $total['total_selling_price'];
$sub += $total['total_buying_price'];
$profit = $sum - $sub;
}
What I'm trying to do is sum up everything in the sales array and subtract it by everything in the costs array (represented by variable $sub) in order to generate profit. However, I'm unable to, and I get the following error:
UNDEFINED VARIABLE: PROFIT.
I've declared a profit variable within the foreach, so can someone tell me why my variable is considered undefined?

Assign $profit = 0 out of loop.
Also validate totals before iterating.
if(is_array($totals)){
foreach($totals as $total ){
// write your code here
}
}

Related

How to update array based on values in another array

I get the error Undefined index: item_total on the line $totals['item_total'] += (float)$quantity; I want $totals array to contain the $mycart summarized quantity data by Product.
$mycart = array();
$mycart[0]['product'] = 'ProductA';
$mycart[0]['quantity'] = 10;
$mycart[1]['product'] = 'ProductA';
$mycart[1]['quantity'] = 4;
$mycart[2]['product'] = 'ProductB';
$mycart[2]['quantity'] = 8;
$mycart[3]['product'] = 'ProductB';
$mycart[3]['quantity'] = 8;
$totals = array();
foreach ($mycart as $row)
{
$product = $row['product'];
$quantity = $row['quantity'];
$totals['item_total'] += (float)$quantity;
}
In php you can create an array index by $totals['item_total'] = value;. And you cannot use an array index in an expression if it has not been "initialized". What do you see when you write this statement out $totals['item_total'] += (float)$quantity; "long hand"? It is just a shortcut for $totals['item_total'] = $totals['item_total'] + (float)$quantity;. In the right-hand expression $totals['item_total'] has not been initialized, thus program gives "Undefined index" message.
Your problem comes from using increment with an undefined variable
$totals['item_total'] += (float)$quantity;
The reason for this is that increment does a read (to get the current value) of the variable, before increment it. Which makes sense because we need to know it's current value before we can add 1 to it.
Now because that variable is not defined, you get an error message Undefined index: item_total". Which also makes sense because we cannot get the value of something (read it) that has not been defined, because it doesn't exist yet.
To further illustrate this, we can manually increment without the += like this:
$totals['item_total'] = $totals['item_total'] + 1;
We should agree this is the same as $totals['item_total'] += 1 as they give the same value, but here you can see how we must reference the previous value of that variable, which is the same thing that += must do. And in the same line of reason we cannot read it if it's not defined.
#Psudo for $var = $var + 1
write = read + 1
When simply assigning like this:
$totals['item_total'] = 0;
There is no reading (of an undefined value, as we know what 0 is) that takes place, so PHP is fine with that variable not existing and just creates it. Some languages are not that forgiving. What I mean here is some languagues you would need to first define $totals as an array, and then add stuff to it. In PHP $totals doesn't even need to exist to do $totals['item_total'] = 0;
So as others noted you need to define it with a value of 0 before hand, that way when the read is done it will know it's 0 and you wont see the error.
$totals['item_total'] = 0;
//or $totals = ['item_total' => 0];
foreach ($mycart as $row)
{
$product = $row['product'];
$quantity = $row['quantity'];
$totals['item_total'] += (float)$quantity;
}
echo $totals['item_total'];
Output
30
Sandbox
PHP is actually very forgiving about undefined variables, but in cases where it must first read that variable, it must be defined beforehand.
UPDATE
Based on this comment
I want it summed by product -- ProductA = 14 and ProductB = 16.
You can do it this way:
$mycart = array();
$mycart[0]['product'] = 'ProductA';
$mycart[0]['quantity'] = 10;
$mycart[1]['product'] = 'ProductA';
$mycart[1]['quantity'] = 4;
$mycart[2]['product'] = 'ProductB';
$mycart[2]['quantity'] = 8;
$mycart[3]['product'] = 'ProductB';
$mycart[3]['quantity'] = 8;
$totals = array();
foreach ($mycart as $row)
{
$key = $row['product'];
if(!isset($totals[$key])){
$totals[$key] = $row;
// $totals[$key] = $row['quantity']; //just [key=>quantity] no inner array
}else{
$totals[$key]['quantity'] += $row['quantity'];
// $totals[$key] += $row['quantity']; //just [key=>quantity] no inner array
}
}
print_r($totals);
Output
Array
(
[ProductA] => Array
(
[product] => ProductA
[quantity] => 14
)
[ProductB] => Array
(
[product] => ProductB
[quantity] => 16
)
)
/*
without the inner array
Array
(
[ProductA] => 14
[ProductB] => 16
)
*/
Sandbox
See my comments in the code on how to remove the inside array if you want just the Key and it's total quantity. If you do want the inner arrays but not the top level key (product), you can do this to remove those.
//after the loop
$totals = array_values($totals); //resets array keys to numbered keys
This will replace the ProductA and ProductB keys with 0 and 1.
Enjoy.
Simply add this line right before foreach:
$totals['item_total']=0;

How to add the values from a foreach loop php

I have and foreach loop that outputs the totals I want to add when i echo the $val_tex it outputs in one number like "4911165" but if I echo it with a break tag it gives me the right values. It looks like
49
1
1
1
65
My question is how to get the sum of all the values which should equal "117"
$val_tex = array();
foreach ( $get_seller as $keys ) {
$val_tex = $keys['total'];
}
You have to add them together in the foreach loop - there's a simple way to do that $total += $keys['total']; It's just a simpler way of saying $total = $total + $keys['total'];
There are also other ways - $total = array_sum(array(1,2,3,4)); // == 10 for example. To get the sum from a single column, you get an array that only contains the values from the specific column first:
// an array of the values from that column
$arrayTotall = array_column($keys, 'total');
$total = array_sum($arrayTotals);
Your for each needs another variable to add them:
foreach ( $get_seller as $keys ) {
$val_tex = $keys['total'];
$sum = += $val_tex
//or...
$val_tex += $keys['total'];
//depending on how you want to us val_tex
}
The .= adds the value to previous value instead of overwriting it.

best way to loop calculations in php

i want to calculate two operations with the help of loop. They are already working and providing result i need. But i want them to look more like coding. So if anybody can help them with the help of for in php
for($i=0;i<something;$i++){
$temp_calc = ;
}
here are two statements.
In first statement length of array is 9.
In second statement length of array is 12.
both statements to be solved in different for loop as they are totally different questions.
$temp_calc = 10*$temp_array[0]+9*$temp_array[1]+8*$temp_array[2]+7*$temp_array[3]+6*$temp_array[4]+5*$temp_array[5]+4*$temp_array[6]+3*$temp_array[7]+2*$temp_array[8];
$temp_calc = 1*$temp_array[0]+3*$temp_array[1]+1*$temp_array[2]+3*$temp_array[3]+1*$temp_array[4]+3*$temp_array[5]+1*$temp_array[6]+3*$temp_array[7]+1*$temp_array[8]+3*$temp_array[9]+1*$temp_array[10]+3*$temp_array[11];
Thanks in advance
It will be a little simpler to use a foreach loop rather than a for loop. If you specifically need to use a for loop because it is a requirement of an assignment, you can check the PHP documentation. There are some examples there of using a for loop to loop over an array. This is a common and basic control structure and it will be more valuable for you to really understand how to use it. The more important part is what goes on inside the loop. There are multiple ways to do this, but here are some basic examples.
First one:
// initialize multiplier and result outside the loop
$multiplier = 10;
$result = 0;
// loop over the values
foreach ($temp_array as $value) {
// add the value * multiplier to the result and decrement the multiplier
$result += $value * $multiplier--;
}
Second one
// initialize multiplier and result outside the loop
$multiplier = 1;
$result = 0;
// loop over the values
foreach ($temp_array as $value) {
// add the value * multiplier to the result
$result += $value * $multiplier;
// switch the multiplier to the alternating value
if ($multiplier == 1) {
$multiplier = 3;
} else {
$multiplier = 1;
}
// The switch can be done more simply using a ternary operator like this:
// $multiplier = $multiplier == 1 ? 3 : 1;
}
for both issues:
$temp_array = array(2,2,2,2,2,2,2,2,2);//sample
function calc_1($temp_array){//first
$total=0;
$count = count($temp_array)+1;
foreach($temp_array as $value){
$total += $count*$value;
$count-=1;
}
return $total;
}
function calc_2($temp_array){//second
$total=0;
foreach($temp_array as $k=>$value){
$total += ($k%2==0) ? 1*$value : 3*$value;//when is even or odd
}
return $total;
}
var_dump(calc_1($temp_array));//resp1
var_dump(calc_2($temp_array));//resp2
If your array is called $myArray, then:
/*Since I can't know what the sequence of the values are that you
are multiplying, and because you might need other sequences in the
future, a function was developed that chooses which sequence you
want to multiply.*/
function findSomeValues($arraySize)
{
switch ($arraySize) {
case 9:
{
$someValues = array(10,9,8,7,4,5,4,3,2);
}
break;
case 12:
{
$someValues = array(1,3,1,3,1,3,1,3,1,3,1,3);
}
break;
default:
$someValues = array();
}
return $someValues;
}
/*This following function then finds how big your array is, looks
for a sequence stored in the findSomeValues function. If a sequence
exist for that array size (in this case if you have an array either
9 or 12 elements long), the result will be calculated and echoed. If
the sequence was not found, an error message would be echoed.*/
function multiplyValues($myArray) {
$result = 0;
$arraySize = count($myArray);//obtaining array size
$someValues = findSomeValues($arraySize);//obtaining sequence to multiply with
if (count($someValues)>0)
{
for($i=0;i<$arraySize;$i++){
$result += $myArray[i]*$someValues[i];
}
echo "result = ".$result."<br>";//result message
}
else
{
echo "you are missing some values<br>";//error message
}
}
Let me know if that worked for you.
Alternative:
If you prefer something a bit simpler:
//this array holds the sequences you have saved:
$sequenceArray = array(
9 => array(10,9,8,7,4,5,4,3,2),
12 => array(1,3,1,3,1,3,1,3,1,3,1,3)
);
//this function does the multiplication:
function multiplyValues($myArray)
{
$arraySize = count($myArray);
for($i=0;i<$arraySize;$i++){
$result += $myArray[i]*$sequenceArray[i];
}
echo "result = ".$result."<br>";//result message
}
For your result
$temp_calc = 10*$temp_array[0]+9*$temp_array[1]+8*$temp_array[2]+7*$temp_array[3]+6*$temp_array[4]+5*$temp_array[5]+4*$temp_array[6]+3*$temp_array[7]+2*$temp_array[8];
You should have for loop as following. It will run the loop till 8th index of your temp_array and multiply each index value with $i and sum up in a variable $temp_calc_1.
<?php
$temp_calc_1 = 0;
for($i=0;$i<9;$i++){
$temp_calc_1 = $temp_calc_1 + ( 10-$i)*$temp_array[$i] ;
}
For your second result
$temp_calc = 1*$temp_array[0]+3*$temp_array[1]+1*$temp_array[2]+3*$temp_array[3]+1*$temp_array[4]+3*$temp_array[5]+1*$temp_array[6]+3*$temp_array[7]+1*$temp_array[8]+3*$temp_array[9]+1*$temp_array[10]+3*$temp_array[11];
The above should be converted to the following loop, this will run loop till your 12th index of temparrayand do the calculation. This time it will multiply each index value of temparray by either 1 and 3. So first time it will multiply with 1 and next time with 3 and so on
//
$temp_calc_2 = 0;
for($i=0;$i<12;$i++){
$j = $i%2?3:1;
$temp_calc_2 = $temp_calc_2 + $j*$temp_array[$i] ;
}
?>

Making a Sum of a nested array in PHP

I have 3 level nested array and I would like some help to make the generate the sum of its values.
The array goes like
SUM
/ \
A B
/ \ /\
Billed Route Billed Route
/ \ / \
Value Value Value Value
How can i make a sum of the Billed and Route fields?
So far I have this code
foreach($sum as $client)
{
$s = 0;
foreach($client as $stat_name=>$stat_value)
{
$val = 0;
// echo "<br><u><i>";
// echo $stat_name;
// echo "</u></i><br>";
foreach($stat_value as $value)
{
$val += intval($value);
}
$sum2[$stat_name] += $val;
}
}
I receive an undefine index error on the first loop for each new key.
Have you defined $sum2[$stat_name] as 0 ? If not, you'll get an undefined index error on each iteration of the second foreach loop because you're trying to do += on a value that isn't defined.
Also, if you're trying add the values of Billed and Route then storing them in different parts of an associative array ($sum2[$stat_name]) is an extra step. Just add them together in the same key of the array.
If those are the actual keys in your array, then:
$route = 0;
$billed = 0;
foreach($yourarray['SUM'] AS $ab => $subarray) {
$billed += $subarray['Billed']['Value'];
$route += $subarray['Routed']['Value'];
}
$sum2[$stat_name] += $val;
is the same as:
$sum2[$stat_name] = $sum2[$stat_name] + $val;
^^^^^^^^^^^^^^^^^ undefined the first time you loop
To solve that, you should initialize it:
$sum2[$stat_name] = isset($sum2[$stat_name]) ? $sum2[$stat_name] : 0;
$sum2[$stat_name] += $val;

Getting total percentage inside while loop

For example I have a mysql_num_rows results of 4,8,15,16,23,42 in a query that is inside a while loop of another query. My question is how can I get the percentage per each result of mysql_num_rows inside my while loop? Example: 4,8,15,16,23,42. Total is 108. $sum = 108. Percentage of 4 = 4/$sum = 3.7%, 8 = 8/$sum = 7.4% and so on..
you can store all the values in an array and do the calcs after you have retrieved the data from the database
eg
$datastore = array();
$total = 0;
while(list($amount) = mysql_fetch_row($result)) {
$datastore[] = $amount;
$total += $amount;
}
foreach ($datastore as $amount) {
echo $amount," - ";
printf("%5.2f", $amount/$total);
echo "\r\n";
}
$values = array(4, 8, 15, ...);
$sum = array_sum($values);
foreach($values as $value) {
echo ($value / $sum) * 100;
}
CodePad.
So you are saying that you want the $sum before the individual results right? You could do a simple additional query to get the sum before you pull out the individual results. Use the SUM aggregate function. It is probably also possible to get the percentage in your SQL results. That would mean a slightly more complex query, but not an additional query.

Categories