How to calculate NPER in PHP - php

I can't figure out how to calculate NPER in php.
I did not find any article in google.
I'm very weak in math becouse of it i'm asking for help.
This is what i did so far :(
public function Nper($interest, $payment, $loan){
$nperC = Log10($payment/($payment+$loan+$interest))/Log10(1+$interest);
return $nperC;
}
if(isset($_POST['NperSubmit'])){
$calc = new CalculatorModel();
$months = $calc->Nper($_POST['interest'], $_POST['payment'], $_POST['loan']);
echo round($months,2);
}
Working code (From Tijo John answer)
public function Nper($interest, $payment, $loan){
$interest = $interest / 1200;
$nperC = Log10 ($payment/ ($payment- $loan * $interest)) / Log10(1 + $interest);
return $nperC;
}
$calc = new CalculatorModel();
$months = $calc->Nper($_POST['interest'], $_POST['payment'], $_POST['loan']);
echo round($months,2);
Thanks :))

I think you should have change the formula as follows
Log10 ($payment/ ($payment- $loan * $interest)) / Log10(1 + $interest)

Related

Sum times from Array using Carbon

How can i sum times into array using Carbon?
<?php
namespace App\Models;
use Carbon\Carbon;
class Appointment extends BaseModel
{
public static function total_time()
{
$appointments = Appointment::get();
$sumtimes = [];
foreach($appointments as $a){
$dti = Carbon::parse($a->dateinitial);
$dtf = Carbon::parse($a->datefinal);
$time = $dti->diff($dtf)->format('%H:%I:%S');
$sumtimes[] = $time;
}
$sumtimes= sum($sumtimes);
return $sumtimes;
}
inside sum_times, there is a list of times that need to be summed like:
$sum_times[0] = "00:01:18"
$sum_times[1] = "00:03:11"
$sum_times[2] = "01:01:18"
$sum_times[3] = "00:01:28"
I need it to return "01:07:15"
<?php
public static function total_time(): string
{
$seconds = 0;
foreach(Appointment::get() as $appointment){
$dateinitial = Carbon::parse($appointment->dateinitial);
$datefinal = Carbon::parse($appointment->datefinal);
$seconds += $datefinal->diffInSeconds($dateinitial);
}
return gmdate('H:i:s', $seconds);
}
Also you must set for your fields (dateinitial, datefinal) cast datetime for automated parsing to Carbon type. Docs for date casts.
Each result of diff can be continuously added to a datum. At the end of the loop we get the sum as the difference from the base date to the date. Carbon is an extension of DateTime. I show the sample code with the base class so that it is reproducible for everyone.
$data = [
['from' => '2022-03-01 16:00', 'to' => '2022-03-02 12:00'], //20:00:00
['from' => '2022-03-02 12:30', 'to' => '2022-03-02 22:02'], //09:32:00
]; //total 29:32:00
$basis = '2000-01-01';
$dateBase = date_create('2000-01-01');
$date = clone $dateBase;
foreach($data as $dates){
$dateFrom = date_create($dates['from']);
$dateTo = date_create($dates['to']);
$diff = $dateFrom->diff($dateTo);
$date->add($diff);
}
$totalDiff = $dateBase->diff($date);
$hours = $totalDiff->d *24 + $totalDiff->h; //days * 24 + hours
echo 'Sum: '.$hours.$totalDiff->format(':%I:%S');
//Sum: 29:32:00
Try self on 3v4l.org

calculating negative and positive hours

I have durations in %RH:i:s format (like +00:00:00 or -00:00:00) and I want to add or subtract them (with the negative) and not in 24 hours
Ex :
1/ (09:30:15+(-10:00:00)) = -01:30:15.
2/ 22:00:00 + 03:00:00 = 25:00:00 (not 01:00:00 +1day)
Any idea ? Thanks in advance !
EDIT:
Finally did it. Don't know if it's the real right way to do it but it works pretty well. Found it by the help of another function found on a forum.
function calc_hours($hour1,$hour2){
$si1 = $hour1[0]; $si2 = $hour2[0];
$hour1 = substr($hour1,1,8);
$hour2 = substr($hour2,1,8);
$secondes1=intval($si1.heure_to_secondes($hour1));
$secondes2=intval($si2.heure_to_secondes($hour2));
$somme=intval($secondes1+$secondes2);
//transfo en h:i:s
$s= ($somme % 60);
$m1= (($somme-$s) / 60);
$m= ($m1 % 60);
$h= (($m1-$m) / 60);
if($somme > 0) { $sif = '+'; }
$resultat=sprintf("%02d", $h).":".sprintf("%02d", abs($m)).":".sprintf("%02d", abs($s))."";
return $sif.$resultat;
}
function heure_to_secondes($heure){
$array_heure=explode(":",$heure);
$secondes=3600*$array_heure[0]+60*$array_heure[1]+$array_heure[2];
return $secondes;
}
Call it like : calc_hours('+27:45:16','-02:35:12');
Finally did it. Don't know if it's the real right way to do it but it works pretty well. Found it by the help of another function found on a forum.
function calc_hours($hour1,$hour2){
$si1 = $hour1[0]; $si2 = $hour2[0];
$hour1 = substr($hour1,1,8);
$hour2 = substr($hour2,1,8);
$secondes1=intval($si1.heure_to_secondes($hour1));
$secondes2=intval($si2.heure_to_secondes($hour2));
$somme=intval($secondes1+$secondes2);
//transfo en h:i:s
$s= ($somme % 60);
$m1= (($somme-$s) / 60);
$m= ($m1 % 60);
$h= (($m1-$m) / 60);
if($somme > 0) { $sif = '+'; }
$resultat=sprintf("%02d", $h).":".sprintf("%02d", abs($m)).":".sprintf("%02d", abs($s))."";
return $sif.$resultat;
}
function heure_to_secondes($heure){
$array_heure=explode(":",$heure);
$secondes=3600*$array_heure[0]+60*$array_heure[1]+$array_heure[2];
return $secondes;
}
Call it like : calc_hours('+27:45:16','-02:35:12');

I'm trying to print out something like "This is the prices with taxes" + the random number and the tax [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to print out something like "This is the prices with taxes" + the random number and the tax.
<!DOCTYPE html>
<html>
<body>
<?php
$tax=0.06;
function random(){
echo rand(1,100);
}
$prices = array();
$taxPrices = array();
for ($i =0; $i< 5; $i++) {
$prices[$i]= random();
}
echo "The prices with the taxes";
for ($i=0; $i<count($prices); $i++) {
$taxPrices[$i]=$prices[$i] * $tax;
echo "<br>$prices[$i] = ".$taxPrices[$i];
}
?>
</body>
</html>
Your function is echoing a value instead of returning it.
function random(){
echo rand(1,100);
}
So...
$prices[$i]= random();
this won't work.
Do this to your function and you should get something going.
function random(){
return rand(1,100);
}
Also, your echo is missing brackets. Use this:
echo "<br>{$prices[$i]} = ".$taxPrices[$i];
Take a look: http://ideone.com/nmbcqG
You could use a more OO approach. For this example, we have a constant declaring the tax amount and a constant declaring the currency prefix. There is two methods: each time we run the createPrice() method, it will generate a random price; each time we run the getPrices() method, it will output all prices with tax added.
Let's take a look at our class (or see a full working version at 3v4l.org)
class Prices {
CONST TAX = 0.6;
CONST PREFIX = '£';
private $TaxPrices = [];
public function createPrice() {
$this->TaxPrices[] = rand(1,100);
return $this;
}
public function getPrices() {
foreach($this->TaxPrices as $_price) {
echo self::PREFIX . $_price * self::TAX . '.00';
}
}
}
We can now instance this class and use the object like so:
$p = new Prices();
for($i = 0; $i <= 5; $i++) {
$p->createPrice();
}
echo 'This is the prices with tax:';
$p->getPrices();
Despite the error that Phiter mentioned there are more things that could be done better.
It's really not needed to create the function only for rand(0,100)
You should not put count() or any other function inside the second argument of for loop unless its value changes. The count value won't change in your case so it can be declared outside as a variable for inside in first argument. See example.
Price with tax is rather 1 + $tax => 1.06 which is 106%. So example when you have number 100 then the price + tax 6% would be 106 so 100 * (1 + 0.06) is proper equatation.
If you format your code according to PSR rules is more readable.
See the code below:
<?php
$tax = 0.06;
$prices = [];
$taxPrices = [];
for ($i = 0; $i < 5; ++$i) {
$prices[$i] = rand(1, 100);
}
echo "The prices with the taxes: <br>";
for ($i = 0, $count = count($prices); $i < $count; ++$i) {
$taxPrices[$i] = $prices[$i] * (1 + $tax);
echo "$prices[$i] = $taxPrices[$i] <br>";
}
Example Output:
The prices with the taxes:
54 = 57.24
60 = 63.6
81 = 85.86
23 = 24.38
68 = 72.08

Gauss-Boaga to WGS84

I'm trying to convert some coordinates from Gauss-Boaga to WGS84. Here's what I've done (PHP):
function gaussToLatLng($Eutm, $Nutm){
// parametri che dipendono dal fuso ovest
$l0 = 9;
$fraz = $Nutm/111092.0821;
echo "$fraz ";
$A= $fraz +
(0.1449300705 * sin(deg2rad(2*$fraz))) +
(0.0002138508 * sin(deg2rad(4*$fraz))) +
(0.0000004322 * sin(deg2rad(6*$fraz)));
$v = sqrt(1 + (0.0067681702 * cos(deg2rad($A)) * cos(deg2rad($A)) ) );
$y = $Eutm - 500000;
$B = rad2deg(atan( ($v * sinh(deg2rad($y/6397376.633)) ) / cos(deg2rad($A))));
$lng = rad2deg(atan(tan(deg2rad($A)) * cos(deg2rad($v * $B))));
$lat = $B + $l0;
echo "A=$A, B=$B \n";
return array(
'lat' => $lat,
'lng' => $lng
);
}
Using as input (1517140, 5036970), I get (9.2271558768758 45.485183518206) while with this online tool I calculated that I should have (9.2189597, 45.4859253) (about 1 Km of difference).
Could you help me spot the error in my code?
Solved using a PHP library: proj4php, using the definition for Gauss Boaga fuso Ovest found here.
Those guys are awesome!

Youtube playlist all videos duration show in php

i want to equal youtube playlist all videos time from this link http://gdata.youtube.com/feeds/api/playlists/PLCK7NnIZXn7gGU5wDy9iKOK6T2fwtGL6l. here have time code like this time='00:05:11.500' .. i want to get all videos time from php then its show like this from php
show it like this : 2:10:50 (2=hours,10=minutes,50=seconds)
i want to variable from php for like this one. plzz help for this post thanks. i tried to do that.. but i can do this.. if someone can plz help me.. if have 4 videos, want to equal all videos time and then want to show all duration from php only
Ok, here's an answer that solves the problem assuming you have no code whatsoever, and no intention of
trying do experiment yourself.
You will probably not be able to use this for anything else than the exact problem described:
adding all the durations of this feed together and displaying it as hours:minutes:seconds
<?php
$total_seconds = 0;
$dom = new DOMDocument();
$dom->loadXML(file_get_contents('http://gdata.youtube.com/feeds/api/playlists/PLCK7NnIZXn7gGU5wDy9iKOK6T2fwtGL6l'));
$xpath = new DOMXPath($dom);
foreach ($xpath->query('//yt:duration/#seconds') as $duration) {
$total_seconds += (int) $duration->value;
}
Then you display $total_seconds in your format. Here's two options:
assuming that hours will never be larger than 24
echo gmdate("H:i:s", $total_seconds);
allowing total time to be larger than 24 hours
echo (int) ($total_seconds / 3600) . ':' . (int) ($total_seconds / 60) % 60 . ':' . $total_seconds % 60;
Keep in mind: This code does exactly ZERO error checking. Things that can go wrong:
The PHP configuration may not allow http stream wrapper
The PHP build might not have Dom enabled
The XML feed may be unavailable
The XML feed might not contain any entries
EDIT:
I took a closer look at the feed, and it seems the "time" entries are just pointers for the thumbnails. The actual duration for a video is set in seconds <yt:duration seconds='667'/> so you could just add them together as integers and then use the DateTime class to convert to whatever your format is. Example here.
END EDIT
First of all, to get all the times, you could need an atom feed reader in PHP. There are plenty out there. Do not try to parse the XML, ATOM is a well known standard that should be easily used (if you really only want the times, you could go with an xpath query).
Now that you have all the times at your disposal, you need a way to add them up easily, preferably without messing with nested loops and if-statements.
Here's a class that represents a single time entry for a single video:
final class Duration
{
private $hours;
private $minutes;
private $seconds;
private $centis;
/* we don't want any Durations not created with a create function */
private function __construct() {}
public static function fromString($input = '00:00:00.000') {
$values = self::valuesFromString($input);
return self::fromValues($values['hours'], $values['minutes'], $values['seconds'], $values['centis']);
}
public function addString($string) {
$duration = self::fromString($string);
return $this->addDuration($duration);
}
public function addDuration(Duration $duration) {
// add the durations, and return a new duration;
$values = self::valuesFromString((string) $duration);
// adding logic here
$centis = $values['centis'] + $this->centis;
$this->fixValue($centis, 1000, $values['seconds']);
$seconds = $values['seconds'] + $this->seconds;
$this->fixValue($seconds, 60, $values['minutes']);
$minutes = $values['minutes'] + $this->minutes;
$this->fixValue($minutes, 60, $values['hours']);
$hours = $values['hours'] + $this->hours;
return self::fromValues($hours, $minutes, $seconds, $centis);
}
public function __toString() {
return str_pad($this->hours,2,'0',STR_PAD_LEFT) . ':'
. str_pad($this->minutes,2,'0',STR_PAD_LEFT) . ':'
. str_pad($this->seconds,2,'0',STR_PAD_LEFT) . '.'
. str_pad($this->centis,3,'0',STR_PAD_LEFT);
}
public function toValues() {
return self::valuesFromString($this);
}
private static function valuesFromString($input) {
if (1 !== preg_match('/(?<hours>[0-9]{2}):(?<minutes>([0-5]{1}[0-9]{1})):(?<seconds>[0-5]{1}[0-9]{1}).(?<centis>[0-9]{3})/', $input, $matches)) {
throw new InvalidArgumentException('Invalid input string (should be 01:00:00.000): ' . $input);
}
return array(
'hours' => (int) $matches['hours'],
'minutes' => (int) $matches['minutes'],
'seconds' => (int) $matches['seconds'],
'centis' => (int) $matches['centis']
);
}
private static function fromValues($hours = 0, $minutes = 0, $seconds = 0, $centis = 0) {
$duration = new Duration();
$duration->hours = $hours;
$duration->minutes = $minutes;
$duration->seconds = $seconds;
$duration->centis = $centis;
return $duration;
}
private function fixValue(&$input, $max, &$nextUp) {
if ($input >= $max) {
$input -= $max;
$nextUp += 1;
}
}
}
You can create a new Duration only by calling the static factory fromString(), and that accepts only strings in the form "00:00:00.000" (hours:minutes:seconds.milliseconds):
$duration = Duration::fromString('00:04:16.250');
Next, you can add another string or an actual duration object, to create a new Duration:
$newDuration = $duration->addString('00:04:16.250');
$newDuration = $duration->addDuration($duration);
The Duration object will output it's own duration string in the format '00:00:00.000':
echo $duration;
// Gives
00:04:16.250
Or, if you're interested in the separate values, you can get them like so:
print_r($duration->toValues());
// Gives
Array
(
[hours] => 0
[minutes] => 4
[seconds] => 16
[milliseconds] => 250
)
Final example for using this in a loop to get the total video time:
$allTimes = array(
'00:30:05:250',
'01:24:38:250',
'00:07:01:750'
);
$d = Duration::fromString();
foreach ($allTimes as $time) {
$d = $d->addString($time);
}
echo $d . "\n";
print_r($d->toValues());
// Gives
02:01:45.250
Array
(
[hours] => 2
[minutes] => 1
[seconds] => 45
[milliseconds] => 250
)
For questions on why I used a final class with private constructor:
I wrote this as an exercise for myself, following Mathias Veraes's blog post on "named constructors".
Also, I couldn't resist adding his "TestFrameworkInATweet" as well:
function it($m,$p){echo ($p?'✔︎':'✘')." It $m\n"; if(!$p){$GLOBALS['f']=1;}}function done(){if(#$GLOBALS['f'])die(1);}
function throws($exp,Closure $cb){try{$cb();}catch(Exception $e){return $e instanceof $exp;}return false;}
it('should be an empty duration from string', Duration::fromString() == '00:00:00.000');
it('should throw an exception with invalid input string', throws("InvalidArgumentException", function () { Duration::fromString('invalid'); }));
it('should throw an exception with invalid seconds input string', throws("InvalidArgumentException", function () { Duration::fromString('00:00:61:000'); }));
it('should throw an exception with invalid minutes input string', throws("InvalidArgumentException", function () { Duration::fromString('00:61:00:000'); }));
it('should add milliseconds to seconds', Duration::fromString('00:00:00.999')->addString('00:00:00.002') == Duration::fromString('00:00:01.001'));
it('should add seconds to minutes', Duration::fromString('00:00:59.000')->addString('00:00:02.000') == Duration::fromString('00:01:01.000'));
it('should add minutes to hours', Duration::fromString('00:59:00.000')->addString('00:02:00.000') == Duration::fromString('01:01:00.000'));
it('should add all levels up', Duration::fromString('00:59:59.999')->addString('00:01:01.002') == Duration::fromString('01:01:01.001'));
$duration = Duration::fromString('00:00:01.500');
it('should add a Duration', $duration->addDuration($duration) == '00:00:03.000');

Categories