else if not working in - php

if condition matches but else if condition is not working when i insert $total_salary = 10000 and $salary_type = NO.
if ($this->request->is('post')) {
$DATA = $this->data;
$employee_salary = $this->Salary->save($DATA);
$total_salary = $employee_salary['Salary']['salary'];
$salary_type = $employee_salary['Salary']['salary_in_ctc'];
echo $total_salary . $salary_type;
if (($total_salary > 15000) && ($salary_type === 'YES')) {
$pf_company = 1500;
$pf_employee = 1500;
$percent = 0.62;
$gross_salary = ($total_salary - $pf_company);
$base_salary = ($percent * $gross_salary);
$HRA = ($base_salary / 2);
$others = ($gross_salary - ($base_salary + $HRA));
$inhand_salary = ($gross_salary - $pf_employee);
} elseif (($total_salary < 15000) && ($salary_type === 'NO')) {
echo'hello';
$pf_company = 1200;
$pf_employee = 1200;
$percent = 0.62;
$gross_salary = ($total_salary - $pf_company);
$base_salary = ($percent * $gross_salary);
$HRA = ($base_salary / 2);
$others = ($gross_salary - ($base_salary + $HRA));
$inhand_salary = ($gross_salary - $pf_employee);
}

try to match the uppercase condition and also check for white space in you conditions.
strtoupper(trim($salary_type))

The possible second issue could be:
As you are checking the datatype also in the condition $salary_type ==='NO' and in the post you stated you are passing $salary_type = NO. which doesn't seems to be a string type.
Please try removing one = from condition or passing NO as a string to validate the condition

Related

Can If Statment created based on loop?

For example
$InitArray[1] = 4;
$InitArray[2] = 5;
$InitArray[3] = 6;
I want to make if statment with that syntax
if($Type = /* key */){
$Position = /* value */
}
which means
if($Type = 1){
$Position = 4;
}
if($Type = 2){
$Position = 5;
}
if($Type = 3){
$Position = 6;
}
How to make that if statment through array loop?
Edit :
Array isn't static , User put his own array
,It Could be like that for example
$InitArray[4] = 34;
$InitArray[5] = 13;
or
$InitArray[6] = 12;
$InitArray[13] = 84;
$InitArray[52] = 23;
$InitArray[78] = 10;
what I mean is something like this
foreach($InitArray as $TypeWritten => $PositionWritten){
if($Type = $TypeWritten){
$Position = $PositionWritten;
}
}
The Equal comparison operator in php is double equal sign ==. So you need to at least change all if statement to use == instead of =.
foreach($InitArray as $TypeWritten => $PositionWritten){
if($Type == $TypeWritten){
$Position = $PositionWritten;
// some code to use the $Position variable ...
// ...
}
}
You're just missing the correct comparison operator. Just change the = into == (or === if the variables you are comparing are of the same type),
foreach($InitArray as $TypeWritten => $PositionWritten){
if($Type == $TypeWritten){
$Position = $PositionWritten;
}
}
Hope this helps,

85/5000 Asynchronous equation in PHP: a variable depends on another that has not yet been declared

I have a sum in my code that needs the return of a function, but the return of this function depends that the sum is already ready, because it uses a parameter that is still going to be created, can you solve it?
It's a calculator made in excel and I'm programming, but excel is that way and it works, but when I went to the code I got caught up in that problem.
//See the code:
public function valorRenda($rendaMensal, $valorEntrada, $tempoMeses, $imovelTipo){
$resultado = array();
$resultado['tipoSimulacao'] = 'rendaCliente';
$taxaMensal = $this->taxaPorTipo('rendaCliente', $imovelTipo, $rendaMensal) / 100;
//Cálculo do valor da primeira parcela
$primeiraParcela = $rendaMensal * 0.3;
//Calcula valor máximo do financiamento
$multiplicador = 0.5;
$i = 1;
for ($i = 1; $i <= 9999999999; $i++) {
$amortizacao = ($i * $multiplicador) / $tempoMeses;
$juros = (($i * $multiplicador) * ($taxaMensal));
$valor = $amortizacao + $juros + $this->custoMensal($valorImovel,$valorEntrada);
if ($valor >= $primeiraParcela) {
$projecao = ($i * $multiplicador) + $valorEntrada;
$valorImovel = ($projecao * $primeiraParcela / $valor);
break;
}
}
$financiamentoMaximo = round($valorImovel);
$financiamentoMaximo = $this->formatoReal($financiamentoMaximo);
$resultado['financiamentoMaximo'] = $financiamentoMaximo;
$resultado['financiamentoMaximoFormatado'] = $this->formatoReal($financiamentoMaximo, false);
//Calcula a primeira parcela
$primeiraParcelaSemTaxas = $primeiraParcela - $this->custoMensal($valorImovel,$valorEntrada);
$primeiraParcelaSemTaxas = round($primeiraParcelaSemTaxas, 2);
$primeiraParcelaSemTaxas = $this->formatoReal($primeiraParcelaSemTaxas);
$resultado['primeiraParcela'] = $primeiraParcelaSemTaxas;
$resultado['primeiraParcelaFormatado'] = $this->formatoReal($primeiraParcelaSemTaxas, false);
$primeiraParcelaTotal = $primeiraParcela;
$primeiraParcelaTotal = round($primeiraParcelaTotal, 2);
$primeiraParcelaTotal = $this->formatoReal($primeiraParcelaTotal);
$resultado['primeiraParcelaTotal'] = $primeiraParcelaTotal;
$resultado['primeiraParcelaTotalFormatado'] = $this->formatoReal($primeiraParcelaTotal, false);
$valorUltimaParcela = ((($valorImovel - $valorEntrada) - ((($valorImovel - $valorEntrada) / $tempoMeses) * ($tempoMeses - 1))) + ((($valorImovel - $valorEntrada) - ((($valorImovel - $valorEntrada) / $tempoMeses) * ($tempoMeses - 1)))) * $taxaMensal) + $this->custoMensal($valorImovel,$valorEntrada);
$ultimaParcelaSemTaxas = $valorUltimaParcela - $this->custoMensal($valorImovel,$valorEntrada);
$ultimaParcelaSemTaxas = round($ultimaParcelaSemTaxas, 2);
$ultimaParcelaSemTaxas = $this->formatoReal($ultimaParcelaSemTaxas);
$resultado['ultimaParcela'] = $ultimaParcelaSemTaxas;
$resultado['ultimaParcelaFormatado'] = $this->formatoReal($ultimaParcelaSemTaxas, false);
$primeiraParcelaTotal = $valorUltimaParcela;
$primeiraParcelaTotal = round($primeiraParcelaTotal, 2);
$primeiraParcelaTotal = $this->formatoReal($primeiraParcelaTotal);
$resultado['ultimaParcelaTotal'] = $primeiraParcelaTotal;
$resultado['ultimaParcelaTotalFormatado'] = $this->formatoReal($primeiraParcelaTotal, false);
$resultado['taxa'] = number_format(round(($taxaMensal * 100), 2), 2);
$resultado['periodo'] = $tempoMeses;
$this->incluiCustoMensal($resultado);
return $resultado;
}
//The function:
private function custoMensal($valorImovel, $entradaImovel)
{`enter code here`
$taxa_dfi = ($this->dfi / 100) * $valorImovel;
$taxa_mip = ($this->mip / 100) * ($valorImovel- $entradaImovel);
return $taxa_dfi + $taxa_mip + $this->tac;
}
Where is the problem:
$valor = $amortizacao + $juros + $this->custoMensal($valorImovel,$valorEntrada);
In this line I need to pass $valorImovelto the function custoMensal(), what happens is that the variable $valorImovel has not yet been created because it depends on the variable $valor.

php calculator switching multiplier based on input

Hello I am building a simple computer in php.
It should work in the way that when the user selects number greater than 30, the variable ( in this case m1 ) becomes m2 and so on.
How can i accomplish this?
Thank you in advance
<?php
$m1 = 5 /*prezzo della maglia - price 1*/;
$m2 = 2;/*price when quantity is over a number*/
$m3 = 1;/*price when quantity is over a number*/
$s1 = 3; /*price of print 1*/
$s1 = 3; /*price of print 1 if quantity change*/
$bxs = $_GET['bxs'];
$bs = $_GET['bs'];
$bm = $_GET['bm'];
$bl = $_GET['bl'];
$bxl = $_GET['bxl'];
$b2xl = $_GET['b2xl'];
/*riga del nero*/
$nxs = $_GET['nxs'];
$ns = $_GET['ns'];
$nm = $_GET['nm'];
$nl = $_GET['nl'];
$nxl = $_GET['nxl'];
$n2xl = $_GET['n2xl'];
$somma = $m1*($bxs+$bs+$bm+$bl+$bxl+$b2xl+$nxs+$ns+$nm+$nl+$nxl+$n2xl);
?>
It is simple, but you must provide the user way enter that value.
For example by the GET parameter number
$userInput = $_GET['number'];
Then you only need to create basic if statement. You can read about it at http://php.net/manual/en/control-structures.if.php
$somma = $bxs+$bs+$bm+$bl+$bxl+$b2xl+$nxs+$ns+$nm+$nl+$nxl+$n2xl;
if($userInput <= 30){
$somma *=$m1;
}else if($userInput >30) {
$somma *=$m2;
} else if($userInput > 8779){ // your number : )
$somma *=$m3;
}

Converting Degree, Minutes, Seconds (DMS) to decimal in PHP

Currently, I'm learning to use Google Maps API. From what I read, the API require the latitude and longitude in Decimal Degree (DD).
In my database, the data is stored as DMS.
Example, 110° 29' 01.1"
I would to ask if you guys have any DMS to DD in php. And, the converter must accept from a single string like the example above.
Regards
You can try if this is working for you.
<?php
function DMStoDD($deg,$min,$sec)
{
// Converting DMS ( Degrees / minutes / seconds ) to decimal format
return $deg+((($min*60)+($sec))/3600);
}
function DDtoDMS($dec)
{
// Converts decimal format to DMS ( Degrees / minutes / seconds )
$vars = explode(".",$dec);
$deg = $vars[0];
$tempma = "0.".$vars[1];
$tempma = $tempma * 3600;
$min = floor($tempma / 60);
$sec = $tempma - ($min*60);
return array("deg"=>$deg,"min"=>$min,"sec"=>$sec);
}
?>
Here's one where you pass in the latitude,longitude in DMS values and returns the converted DMS string. Easy and simnple
function DECtoDMS($latitude, $longitude)
{
$latitudeDirection = $latitude < 0 ? 'S': 'N';
$longitudeDirection = $longitude < 0 ? 'W': 'E';
$latitudeNotation = $latitude < 0 ? '-': '';
$longitudeNotation = $longitude < 0 ? '-': '';
$latitudeInDegrees = floor(abs($latitude));
$longitudeInDegrees = floor(abs($longitude));
$latitudeDecimal = abs($latitude)-$latitudeInDegrees;
$longitudeDecimal = abs($longitude)-$longitudeInDegrees;
$_precision = 3;
$latitudeMinutes = round($latitudeDecimal*60,$_precision);
$longitudeMinutes = round($longitudeDecimal*60,$_precision);
return sprintf('%s%s° %s %s %s%s° %s %s',
$latitudeNotation,
$latitudeInDegrees,
$latitudeMinutes,
$latitudeDirection,
$longitudeNotation,
$longitudeInDegrees,
$longitudeMinutes,
$longitudeDirection
);
}
I wrote a PHP function that does what the question asks: converts a string in degrees/minutes/seconds into decimal degrees. It accepts a number of different formats for the string, and honors direction (NSEW).
Here is the code:
<?php
function convertDMSToDecimal($latlng) {
$valid = false;
$decimal_degrees = 0;
$degrees = 0; $minutes = 0; $seconds = 0; $direction = 1;
// Determine if there are extra periods in the input string
$num_periods = substr_count($latlng, '.');
if ($num_periods > 1) {
$temp = preg_replace('/\./', ' ', $latlng, $num_periods - 1); // replace all but last period with delimiter
$temp = trim(preg_replace('/[a-zA-Z]/','',$temp)); // when counting chunks we only want numbers
$chunk_count = count(explode(" ",$temp));
if ($chunk_count > 2) {
$latlng = $temp; // remove last period
} else {
$latlng = str_replace("."," ",$latlng); // remove all periods, not enough chunks left by keeping last one
}
}
// Remove unneeded characters
$latlng = trim($latlng);
$latlng = str_replace("º","",$latlng);
$latlng = str_replace("'","",$latlng);
$latlng = str_replace("\"","",$latlng);
$latlng = substr($latlng,0,1) . str_replace('-', ' ', substr($latlng,1)); // remove all but first dash
if ($latlng != "") {
// DMS with the direction at the start of the string
if (preg_match("/^([nsewNSEW]?)\s*(\d{1,3})\s+(\d{1,3})\s+(\d+\.?\d*)$/",$latlng,$matches)) {
$valid = true;
$degrees = intval($matches[2]);
$minutes = intval($matches[3]);
$seconds = floatval($matches[4]);
if (strtoupper($matches[1]) == "S" || strtoupper($matches[1]) == "W")
$direction = -1;
}
// DMS with the direction at the end of the string
if (preg_match("/^(-?\d{1,3})\s+(\d{1,3})\s+(\d+(?:\.\d+)?)\s*([nsewNSEW]?)$/",$latlng,$matches)) {
$valid = true;
$degrees = intval($matches[1]);
$minutes = intval($matches[2]);
$seconds = floatval($matches[3]);
if (strtoupper($matches[4]) == "S" || strtoupper($matches[4]) == "W" || $degrees < 0) {
$direction = -1;
$degrees = abs($degrees);
}
}
if ($valid) {
// A match was found, do the calculation
$decimal_degrees = ($degrees + ($minutes / 60) + ($seconds / 3600)) * $direction;
} else {
// Decimal degrees with a direction at the start of the string
if (preg_match("/^(-?\d+(?:\.\d+)?)\s*([nsewNSEW]?)$/",$latlng,$matches)) {
$valid = true;
if (strtoupper($matches[2]) == "S" || strtoupper($matches[2]) == "W" || $degrees < 0) {
$direction = -1;
$degrees = abs($degrees);
}
$decimal_degrees = $matches[1] * $direction;
}
// Decimal degrees with a direction at the end of the string
if (preg_match("/^([nsewNSEW]?)\s*(\d+(?:\.\d+)?)$/",$latlng,$matches)) {
$valid = true;
if (strtoupper($matches[1]) == "S" || strtoupper($matches[1]) == "W")
$direction = -1;
$decimal_degrees = $matches[2] * $direction;
}
}
}
if ($valid) {
return $decimal_degrees;
} else {
return false;
}
}
?>
Here it is on Github with test cases: https://github.com/prairiewest/PHPconvertDMSToDecimal
Solved.
<?php
function DMStoDD($input)
{
$deg = " " ;
$min = " " ;
$sec = " " ;
$inputM = " " ;
print "<br> Input is ".$input." <br>";
for ($i=0; $i < strlen($input); $i++)
{
$tempD = $input[$i];
//print "<br> TempD [$i] is : $tempD";
if ($tempD == iconv("UTF-8", "ISO-8859-1//TRANSLIT", '°') )
{
$newI = $i + 1 ;
//print "<br> newI is : $newI";
$inputM = substr($input, $newI, -1) ;
break;
}//close if degree
$deg .= $tempD ;
}//close for degree
//print "InputM is ".$inputM." <br>";
for ($j=0; $j < strlen($inputM); $j++)
{
$tempM = $inputM[$j];
//print "<br> TempM [$j] is : $tempM";
if ($tempM == "'")
{
$newI = $j + 1 ;
//print "<br> newI is : $newI";
$sec = substr($inputM, $newI, -1) ;
break;
}//close if minute
$min .= $tempM ;
}//close for min
$result = $deg+( (( $min*60)+($sec) ) /3600 );
print "<br> Degree is ". $deg*1 ;
print "<br> Minutes is ". $min ;
print "<br> Seconds is ". $sec ;
print "<br> Result is ". $result ;
return $deg + ($min / 60) + ($sec / 3600);
}
?>
If you also want to include the reference, you might want to use this function:
function DMStoDD($ref, $deg, $min, $sec)
{
$n = $deg + (($min * 60 + $sec) / 3600);
if (($ref == "S") or ($ref == "W")) {
return -$n;
} else {
return $n;
}
}
This works very well:
<?php echo "<td> $deg&#176 $min' $sec&#8243 </td>"; ?>
where deg, min and sec are the angular co-ordinates.

Split total into 5 different numbers

Ok what i'm wanting to do is split a number ($row['count']) into 5, this is easy enough if you want equal numbers:
$sum = ($row['count'] / 5);
$fsum = floor($sum);
but I want each number to be different and still add up to total ie $row['count'] how can this be achieved?
Update:
If this helps its to be used to update 5 rows in a database:
$query = "SELECT * FROM foo";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$sum = ($row['count'] / 5);
$fsum = floor($sum);
$id = $row['id'];
$update = "UPDATE foo SET foo1='$fsum', foo2='$fsum', foo3='$fsum', foo4='$fsum', foo5='$fsum' WHERE id='$id'";
mysql_query($update);
}// while
so ideally the $update query would be something like:
$update = "UPDATE foo SET foo1='$fsum1', foo2='$fsum2', foo3='$fsum3', foo4='$fsum4', foo5='$fsum5' WHERE id='$id'";
This is my take:
function randomize($sum, $parts) {
$part_no = count($parts);
$continnue_counter = 0;
while (count(array_unique($parts)) != $part_no) {
$changing = array_rand($parts, 2);
if (($parts[$changing[0]] - 1) == 0 || ($parts[$changing[1]] - 1) == 0) { // don't let them go under 1
++$continnue_counter;
// sometime one element get everything and others even out on 1
// just throw away everything you got so far and start over
if ($continnue_counter > 10) {
$parts = setup($sum, $part_no);
$continnue_counter = 0;
}
continue;
}
$continnue_counter = 0;
$signum = mt_rand(0, 100) % 2 ? 1 : -1;
$delta = $signum * mt_rand(1, min($parts[$changing[0]] - 1, $parts[$changing[1]] - 1)); // -1 to make sure they don't go under 0
$parts[$changing[0]] += $delta;
$parts[$changing[1]] -= $delta;
}
return $parts;
}
function setup($sum, $part_no) {
$parts = array_fill(0, $part_no, (int)($sum / $part_no));
// acount for the reminder of (int) cast
$reminder = $sum - array_sum($parts);
while ($reminder) {
$parts[array_rand($parts)] += 1;
--$reminder;
}
return $parts;
}
$part_no = 5;
$sum = 42;
$parts = randomize($sum, setup($sum, $part_no));
var_export($parts);
print array_sum($parts)
Update:
I've added a version that introduces a little more entropy.
Update2:
The more random one had a tendency to decrement everything to 1 except one part, added an explicit detection to deal with this. Still the algorithm behind it has unknown termination time.

Categories