If-else statement to count some variable - php

I need some help to solved this algorithm problem with How a Person is popular in his city.
My situation
How the algorithm should work like
If a person "mark" has 500 friends in his city out of 500,000.
(500/500,000)*50,000 = 5
So 5 in 50,000 people Know him right.
But When friends count increase the 50,000 should decrease
If "sam" has 1000 friends then
(1000/500,000)*25000 = 5
So 5 in 25000 people know his name
Yes we could implement this in if/else condition
If so then i have to write 500 lines of code.
Is there another way to do this in PHP?
<?php
$totalfriends = 100;
$totali = 5000000;
$name = "Sam";
if ($totalfriends >= 100 && $totalfriends <= 499 ) {
$r = ($totalfriends/$totali)*50000;
echo round($r),' ',"in 50K People on City regonize this Profile";
}else if ($totalfriends >= 500 && $totalfriends <= 999) {
$r = ($totalfriends/$totali)*25000;
echo round($r),' ',"in 25K People on City know".$name;
}else{
echo "";
}
?>

is this what you are looking for?
foreach([100, 500, 543, 1000, 5000, 51000, 500000] as $my_friends)
echo '5 in '. getScoreOf($my_friends) . "<br>";
function getScoreOf($my_friends){
$of = 5;
$total = 5e5; //that's 500,000 ;)
$step = 100; //minimum step, so output is not "4604" but "4600"
$out_of = $total / $my_friends * $of;
return $out_of > $step? round($out_of / $step) * $step: round($out_of);
}
run it in sandbox
edit: solution merged with original code
<?php
$of = 5;
$totalfriends = 100;
$name = "Sam";
echo $of ." in ". getScoreOf($of, $totalfriends) ." people in city know ". $name;
function getScoreOf($of, $my_friends){
$total = 5e6; //that's 5,000,000 ;)
$step = 100; //minimum step, so output is not "4604" but "4600"
$out_of = $total / $my_friends * $of;
return $out_of > $step? round($out_of / $step) * $step: round($out_of);
}

Related

Distribute a payment value through monthly period

Imagine a scenario where monthly rent is 100,000 which is payable at the end of each month.
A tenant then decides to make a payment 350,000 to cater for the current month and those ahead. How do I distribute this amount since I can obviously see here that this amount caters for 3 months and a half month?
Here is what I was trying in PHP but I just can't get the last 50,000 to appear.
$rent = 100000; // rent amount
$amountPaid = 350000; // amount paid by tenant
$length = $amountPaid/$rent; // number of months paid for
for ($c = 1; $c <= $length; $c++)
{
$foreachMonth = $rent;
assignRentFunction($c, $foreachMonth);
}
function assignRentFunction($count, $amt)
{
echo "Month ".$count.': '.$amt."<br>";
}
Steps:
1) Get total months with ceil() function.
2) It will return 4 months. 3 months fully paid and one month paid only 50000.
3) Now, for each loop will add 10000 to total rent paid.
4) if this surpasses the amount paid, get mod which is 50000
$rent = 100000; // rent amount
$amountPaid = 350000; // amount paid by tenant
$length = ceil($amountPaid/$rent); // number of months paid for
$totalRent = 0;
for ($c = 1; $c <= $length; $c++) {
$totalRent += $rent;
$foreachMonth = $rent;
if ($amountPaid < $totalRent) { // Here is the logic, if amount exceeds, use the remaining amount.
$foreachMonth = $amountPaid % $rent;
}
assignRentFunction($c, $foreachMonth);
}
function assignRentFunction($count, $amt) {
echo "Month ".$count.': '.$amt."<br>";
}
**Output:**
Month 1: 100000
Month 2: 100000
Month 3: 100000
Month 4: 50000
$rent= 100000; // rent amount
$amountPaid= 350000; // amount paid by tenant
$length= $amountPaid/$rent; // number of months paid for
for ($c = 1; $c <= ceil($length); $c++)
{
$foreachMonth = 100000;
if($amountPaid>$rent)
{
$rent=$rent;
$amountPaid=$amountPaid-$rent;
}
else
{
$rent=$rent-$amountPaid;
}
assignRentFunction($c, $rent);
}
function assignRentFunction($count, $amt)
{
echo "Month ".$count.': '.$amt."<br>";
}
Since there seems to be a few ways to slice this, I thought I'd throw my hat in the ring also:
for($c = 1; $c<=ceil($amountPaid/$rent); $c++){
assignRentFunction($c, $rent - max(($c * $rent - $amountPaid),0));
}
And now the commented version:
for($month = 1; $month<=ceil($amountPaid/$rent); $month++){
//For each month there is money for rent (using ceil() to account for fractions)
assignRentFunction(
$month,
// The number of the month
$rent
//Show the rent ($rent)
-
//Deduct
max(($month * $rent - $amountPaid),0)
//Any difference if the whole rent for that month hasn't been paid
/**
* This relies on a little hack with the max() function:
* max($var,0) will return 0 if $var is less than 0.
* So we check to see if the sum of rent up to that month ($month * $rent)
* is greater than what was paid ($month * $rent) - $amountPaid.
* If it isn't because it's wrapped in the max,
* the net (negative) number will just be shown as nill.
* If it is, the net positive number will be subtracted
* from the month's rent.
**/
);
}
Change your loop part to
for ($c = 1; $c <= $length; $c++) {
$foreachMonth = $rent;
assignRentFunction($c, $foreachMonth);
}
$fractionalMonth = $length - intval($length);
if ($fractionalMonth)
assignRentFunction($c, $foreachMonth * $fractionalMonth);
Your error was since you're always incrementing $c by one, you wasn't able to get the fractional part for the last month
You can solve your problem like this,
$rent = 100000; // rent amount
$amountPaid = 350000; // amount paid by tenant
$length = ceil($amountPaid / $rent); // number of months paid for
$temp1 = $amountPaid;
for ($c = 1; $c <= $length; $c++) {
if($temp1 < $rent){ // assigning left amount to rent if less than amount left
$rent = $temp1;
}
if($temp1 > $rent){ // checking if amount left is still more than per month rent then minus that rent from pending paid amount
$temp1 = $temp1 - $rent;
}
assignRentFunction($c, $rent);
}
function assignRentFunction($count, $amt)
{
echo "Month " . $count . ': ' . $amt . "<br>";
}
Demo.

Filter negative and positive values out of one variable in PHP

I have a variable in PHP where values from a database are inserted. It’s about money. I need to summarize all negative and positives values separately.
Example:
February, I have:
+ 10
− 10
+100
− 50
− 15
+ 70
+ 80
—
Credits added: 260 Euro
Credits paid: −75 Euro
The variable is named $amound in my PHP file. I really have no clue how to do that.
In Excel, this would be as follows: =SUMMEWENN(E1:E48;"<0")
But here I only have a variable, not fields.
Heres some Code:
$reportdata["tableheadings"] = array("Transaktions-ID","Kunde","Datum","Beschreibung","Betrag");
if ($startdate && $enddate) {
$query = "SELECT tblcredit.*,tblclients.firstname,tblclients.lastname FROM tblcredit INNER JOIN tblclients ON tblclients.id=tblcredit.clientid WHERE tblcredit.date BETWEEN '".db_make_safe_human_date($startdate)."' AND '".db_make_safe_human_date($enddate)."'";
$result = full_query($query);
while ($data = mysql_fetch_array($result)) {
$id = $data["id"];
$userid = $data["clientid"];
$clientname = $data["firstname"]." ".$data["lastname"];
$date = fromMySQLDate($data["date"]);
$description = $data["description"];
$amount = $data["amount"];
$currency = getCurrency($userid);
$amount = formatCurrency($amount);
$overallamount += $amount;
// $overallamountout -= $amount;
// $overallamountin += $overallamount > 0;
$reportdata["tablevalues"][] = array($id,''.$clientname.'',$date,nl2br($description),$amount);
}
Indeed, this is very simple (I assume that all of your variables are strings, e.g. coming from a text file, but even if not it will work):
$var1 = '+80';
$var2 = '-30';
$result = (int)$var1 + (int)$var2;
var_dump($result);
Will result in: "int(50)" => Working fine.
You can do it in the DB
SELECT SUM(numbers) AS sum1 FROM pepa WHERE numbers > 0;
SELECT SUM(numbers) AS sum2 FROM pepa WHERE numbers < 0;
Okay,
its done.
Heres the Code which was used:
$summeGesamt = 0;
$summeEingezahlt = 0;
$summeAusgezahlt = 0;
$summeGesamt = $summeGesamt + $data["amount"];
if ( $data["amount"] >= 0) {
$summeEingezahlt += $data["amount"];
} else {
$summeAusgezahlt += $data["amount"];
}

Calculating Percentages Error

I am trying to fix this percent calculation, however it is just stumping me today.
Here is the code:
$entries = GFAPI::get_entries($form['id'], $search_criteria);
$score = 0;
$max = 0;
$percentage = array();
if(!empty($entries)) {
foreach ($entries as $entry) {
$score = GFSurvey::get_field_score($form_fields, $entry);
$max = end($form_fields['choices']);
if(empty($max['score'])) {
unset($form_fields['choices'][key($form_fields['choices'])]);
$max = end($form_fields['choices']);
}
$max = $max['score'];
$percentage[] = ($score / $max ) * 100;
}
}
$average = round(array_sum($percentage) / count($percentage), 2);
I have the form and i have Not Applicable radio buttons on the form. When a client fills out the form, sometimes on certain questions they need to be N/A because they do not apply and that does not need to counted in the overall total score.
So that is the report generated which the % is incorrect. That percent should read: 94%. In this picture you will see if you click on the graph you can see this:
Graph Once Clicked
It is showing the people who answered this question, and there are 20. There are a total of 5 max points for each person, or in this case I have the N/A box set for blank, which returns 0. What it is doing is totaling all the possible points which are 100. (20 people and 5 max points)
What I need it to do is NOT count the blank fields and in return give me for example in the image Graph Once Clicked there are only 5 people that answered so max points are 25. the total points is 23.5 so 23.5 / 25.
How about this code ? The total percentage of answered questions is in variable $total_percentage.
$entries = GFAPI::get_entries($form['id'], $search_criteria);
$score = 0;
$max = 0;
$total_max = $total_score = 0;
$percentage = array();
if(!empty($entries)) {
foreach ($entries as $entry) {
$score = GFSurvey::get_field_score($form_fields, $entry);
$max = end($form_fields['choices']);
if(empty($max['score'])) {
unset($form_fields['choices'][key($form_fields['choices'])]);
$max = end($form_fields['choices']);
}
$max = $max['score'];
if ($max) {
$total_score += $score;
$total_max += $max;
}
$percentage[] = ($score / $max ) * 100;
}
}
$average = round(array_sum($percentage) / count($percentage), 2);
$total_percentage = ($total_max > 0) ? round($total_score/$total_max/100, 2) : 0;

Vote up down total max

Hey tried to search for similar but guess my english fail me lol, well here is what i need help with, im trying to make a vote system with up/down vote and wanna show it like this
5.3/10
but have no idea how to make total "5.3" not go over 100% = 10 here is my code so far
<?php
$Vote_up = 804;
$Vote_down = 942;
$total = $Vote_up + $Vote_down;
$result = 100;
echo number_format($total/$result,1,",",".") . "/10";
?>
result is 17,5/10
ps. new to php so be easy on me ^^
i am really bad at maths but i think this should be work
$Vote_up = 555;
$Vote_down = 555;
$total = $Vote_up + $Vote_down;
if( $total <= 0 ){
$score = -11;
} else {
$score = (($Vote_up / $total) + ($Vote_down / $total) * 10) * -1;
}
echo floor( $score + 11 ) . '/10';
if someone have a better solution, please i would like to know it - thanks!

PHP formula needed to calculate a simple format

I am trying to take an amount and convert it to a units type format...
For example:
( note: don't worry about the dollar sign )
Total is $400
I need to display it as 4 * 100
Another Example
Total is $450
I need to display it as 4 * 100 | 50 * 1
So another words there are only 100 and 1 units.
I was thinking for 3 hours already and nothing seems to come to mind...Perhaps someone out there has done something similar and already know the answer?
Hoping I am not doing your homework. Try this:
$num = 450;
$ones = $num % 100;
$hundreds = floor($num / 100);
echo "$hundreds * 100 | $ones * 1";
Here's a simple implementation
$amount = 450;
$hundreds = floor($amount / 100);
$ones = $amount % 100;
$string = array();
if( $hundreds )
$string[] = "$hundreds * 100";
if( $ones )
$string[] = "$ones * 1";
echo implode(' | ', $string);
Check out the modulus (%) operator
Here's a simple solution which will only show the units present, you can get rid of the array/join stuff if you always need to show both units:
$total = 400;
$out = array();
$hundreds = floor($total / 100);
if ($hundreds) {
$out[] = $hundreds . ' * 100';
}
$ones = $total % 100;
if ($ones) {
$out[] = $ones . ' * 1';
}
echo join(' | ', $out);
Use the modulus operator to break down the number (this kind of thing is good to learn how to do because you'll need it for many other units conversion tasks like seconds -> minutes & seconds conversion):
$value=450;
$ones = $value % 100;
$hundreds = floor($value / 100);
echo "$hundreds * 100 | $ones * 1\n";

Categories