elseif statement is not working? - php

I write a logic to round value based on fraction part value. When i execute this code, elseif block is not executed. Here is my code
<?php
function roundRating($rating)
{
if($rating>=5 && $rating<0){
$rating=0;
}
$a=(int)$rating/1;
$b= $rating-$a;
if(($b>=.1) && ($b<=.2)){
$b=0;
$rating=$a;
}
elseif(($b>=.3 && $b<=.4)|| ($b>=.6 && $b<=.7)){
$b=.5;
$rating=$a+$b;
}
elseif(($b>=.8) && ($b<=.9)){
$b=1;
$rating=$a+$b;
$a=$rating;
}
else{}
return $rating;
}
echo roundRating(3.3);
?>
for this value 3.3, the output should be 3.5. But currently it will return passed value 3.3 instead of 3.5. Kindly help me to find out the problem in the above code. Thanks in advance.

I've done my own version of the function which might be cleaner, and i think generates the output required:
function roundRating($rating) {
if( $rating > 5) {
return 5; // Note: assuming the >5 case of 0 was a bug and it was meant to cap it to 5
} elseif( $rating < 0 ) {
return 0;
}
$number = floor($rating);
$remainder = $rating * 10 % 10;
if( $remainder <= 2 ) {
return $number;
} elseif( $remainder >= 8 ) {
return $number + 1;
} else {
return $number + 0.5;
}
}
echo roundRating(3.4); // 3.5
echo roundRating( 3.0) ; // 3
echo roundRating( 6) ; // 5
echo roundRating( 3.8) ; // 4

Please follow the following code given bellow.we some times face problem in floating value comparison. So, it is useful to specify how much number we will consider after decimal point. In the following code value of b is specified that it takes only 3 numbers after decimal point.
For details please visit:
is-floating-point-math-broken
To check online please visit:
Online check
function roundRating($rating)
{
if($rating>=5 && $rating<0){
$rating=0;
}
$a=(int)$rating/1;
$b= sprintf('%3f',$rating-$a);
if(($b>=.1) && ($b<=.2)){
$b=0;
$rating=$a;
}
elseif(($b>=.3 && $b<=.4)|| ($b>=.6 && $b<=.7)){
$b=.5;
$rating=$a+$b;
}
elseif(($b>=.8) && ($b<=.9)){
$b=1;
$rating=$a+$b;
$a=$rating;
}
else{}
return $rating;
}
echo roundRating(3.3); // 3.5
?>

Replace your code with below code.
<?php
function roundRating($rating)
{
if($rating >= 5 && $rating < 0){
$rating=0;
}
else
{
$a=(int)$rating/1;
$b= $rating-$a;
echo $a ."</br>";
echo $b."</br>";
if(($b >= 0.1) && ($b <= 0.2)){
$b=0;
$rating=$a;
}
elseif(($b >=0.3 || $b<=0.4) && ($b>=0.6 || $b<=0.7)){
$b=.5;
$rating=$a+$b;
}
elseif(($b>=.8) || ($b<=.9)){
$b=1;
$rating=$a+$b;
$a=$rating;
}
else{}
}
return $rating;
}
echo roundRating(3.3);
?>
Here i have did two change first add else condition your rating calculation work if $rating is not greater than 5 or less than 0. and second in one of your else if condition is change which is given below.
elseif(($b >=0.3 || $b<=0.4) && ($b>=0.6 || $b<=0.7)){
//echo "here";
$b=.5;
$rating=$a+$b;
}
i hope it will helps you.

Floating point numbers have hidden/limited precision in C - so you can't trust them to the last digit. There's more of a writeup on this at http://php.net/manual/en/language.types.float.php
If you were to round it to 1 decimal place, you'll get 3.5:
$b= round($rating-$a, 1);

To start with :
if($rating>=5 && $rating<0)
will always be false . A variable can't be greater than 5 and less than 0 at the same time.
Regarding
elseif(($b>=.3 && $b<=.4)|| ($b>=.6 && $b<=.7)){
$b=.5;
$rating=$a+$b;
}
what practical differece would it make with :
elseif(($b>=.3 && $b<=.7)){
$b=.5;
$rating=$a+$b;
}
unless you write :
else{
$rating+=some_value;// forthe inifinite number of values between .4 & .6?
}
Regarding,
elseif(($b>=.8) && ($b<=.9)){
$b=1;
$rating=$a+$b;
$a=$rating; // This statement is redundant
}
Since you return $rating from the function, $a=$rating; is redundant.
Having said the above things, I feel below would be a much simpler implementation, with results almost identical to desired one :
<?php
function round_rating($rating){
if($rating<0 || $rating>5){
$rating=0;
return $rating;
}
$t_rating=(int)$rating; //$t_rating short for trimmed_rating :)
$dif=$rating-$t_rating; //$dif is the short for difference :)
if($dif <= .2){
return($t_rating);
}
elseif($dif <= .7){
return((float)$t_rating+.5);
}
else{
return((float)$t_rating+1);
}
} // round_rating function ends here :)
/*Test time*/
printf("Round rating for %0.2f : %0.2f\n",6,round_rating(6));
printf("Round rating for %0.2f : %0.2f\n",0.2,round_rating(0.2));
printf("Round rating for %0.2f : %0.2f\n",1.4,round_rating(1.4));
printf("Round rating for %0.2f : %0.2f\n",2.8,round_rating(2.8));
printf("Round rating for %0.2f : %0.2f\n",4.6,round_rating(4.6));
printf("Round rating for %0.2f : %0.2f\n",-1,round_rating(-1));
?>
Output :
Round rating for 6.00 : 0.00
Round rating for 0.20 : 0.00
Round rating for 1.40 : 1.50
Round rating for 2.80 : 3.00
Round rating for 4.60 : 4.50
Round rating for -1.00 : 0.00

Thank you all for your answers. Finally i got the answer. Here is my answer.
function roundRating($rating)
{
if($rating>5 ){
$rating=0;
return $rating;
}
elseif($rating<=0)
{
$x=0;
return $rating;
}
$a=(int)$rating/1;
$b= $rating-$a;
$b= (int)round(($b*10),0);
if($b<=2)
{
$rating=$a;
return $rating;
}
elseif($b>=3 && $b<=7){
$rating=$a+.5;
return $rating;
}
elseif($b>=8){
$rating=$a+1;
return $rating;
}
else{}
}
echo roundRating(3.2); //3
echo roundRating(3.3); //3.5
echo roundRating(3.7); //3.5
echo roundRating(3.8); //4

Related

Migratory Birds solution - PHP-

I wrote this solution for this practice in PHP but it's not work for all case:
Given an array of bird sightings where every element represents a bird type id, determine the id of the most frequently sighted type. If more than 1 type has been spotted that maximum amount, return the smallest of their ids.
arr=[1,1,2,2,3]
Example
There are two each of types 1 and 2 , and one sighting of type .3 Pick the lower of the two types seen twice: type 1.
Function Description
Complete the migratoryBirds function in the editor below.
migratoryBirds has the following parameter(s):
int arr[n]: the types of birds sighted
Returns
int: the lowest type id of the most frequently sighted birds
Input Format
The first line contains an integer,n , the size of arr .
The second line describes arr as n space-separated integers, each a type number of the bird sighted.
Constraints
5 < n < 2 X 10 2
It is guaranteed that each type is 1,2 ,3 ,4 , or 5 .
Sample Input 0
6
1 4 4 4 5 3
Sample Output 0
4
this is my code
function migratoryBirds($arr) {
// Write your code here
$length=count($arr);
$a1=0;$a2=0;$a3=0;$a4=0;$a5=0;
for($i=0; $i < $length; $i++){
if($arr[$i]==1){
$a1++;
}
if($arr[$i]==2){
$a2++;
}
if($arr[$i]==3){
$a3++;
}
if($arr[$i]==4){
$a4++;
}
if($arr[$i]==5){
$a5++;
}
}
if($a1>=$a2 && $a1>=$a3 && $a1>=$a4 && $a1>=$a5){
$result=1;
}
if($a2>=$a1 && $a2>=$a3 && $a2>=$a4 && $a2>=$a5){
$result=2;
}
if($a3>=$a2 && $a3>=$a1 && $a3>=$a4 && $a3>=$a5){
$result=3;
}
if($a4>=$a2 && $a4>=$a3 && $a4>=$a1 && $a4>=$a5){
$result=4;
}
if($a5>=$a2 && $a5>=$a3 && $a5>=$a4 && $a5>=$a1){
$result=5;
}
return $result;
}
How can I solve it?
write your condition like this
if($a1>=$a2 && $a1>=$a3 && $a1>=$a4 && $a1>=$a5){
$result=1;
}
else if($a2>=$a1 && $a2>=$a3 && $a2>=$a4 && $a2>=$a5){
$result=2;
}
else if($a3>=$a2 && $a3>=$a1 && $a3>=$a4 && $a3>=$a5){
$result=3;
}
else if($a4>=$a2 && $a4>=$a3 && $a4>=$a1 && $a4>=$a5){
$result=4;
}
else if($a5>=$a2 && $a5>=$a3 && $a5>=$a4 && $a5>=$a1){
$result=5;
}
else{
$result=1;
}
Given an array of bird sightings where every element represents a bird type id, determine the id of the most frequently sighted type. If more than 1 type has been spotted that maximum amount, return the smallest of their ids.
For this question I wrote a code.
It passed all the test cases.
My code is as follows:
import math
import os
import random
import re
import sys
def migratoryBirds(arr):
x = [0] *(max(arr)+1)
for i in arr:
x[i] += 1
return x.index(max(x))
if name == 'main':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
arr_count = int(input().strip())
arr = list(map(int, input().rstrip().split()))
result = migratoryBirds(arr)
fptr.write(str(result) + '\n')
fptr.close()
Here try this one:
$array = array(1,2 ,3, 4, 5, 4, 3, 2, 2, 1, 3, 4);
$counted = array_count_values($array);
$n = null;
$v = 0;
foreach($counted as $nm => $val) {
if ($val > $v) {
$n = $nm;
$v = $val;
}
}
echo $n;
Hope this will help you.
function migratoryBirds($arr) {
// Write your code here
foreach($arr as $value){
if(isset($new_arr[$value])){
$new_arr[$value] += 1;
}else{
$new_arr[$value] = 1;
}
}
$min_key = '';
$max_val = 0;
for($i=(count($new_arr)); $i>=0; $i--){
if(isset($new_arr[$i])){
if($new_arr[$i] >= $max_val){
$min_key = $i;
$max_val = $new_arr[$i];
}
}
}
return $min_key;
}

PHP | Make a validation check whether the number has a decimal point == x.00 or not

Em, I don't know how to explain this. I hope you'll get the point.
I've variables:
$a = 10; //int
$b = 2.5; //float
$c = $a * $b; //I know this return will be float: 25
From those variables, I want to make a statement as follows:
if (//the value of $c have a decimal point == x.00) {
echo $c;
} else {
echo '';
}
Did you get it? What I want is that when the decimal point of $c is x.00 (like 25.00, 10.00, etc), the $c will be printed. But if the decimal point is NOT x.00 (eg 25.50, 25.7, etc) then $c will NOT be printed.
I've read some references but still don't understand how to do it.
Thank you. I hope you understand what I mean.
PHP has is_integer() - https://www.php.net/manual/en/function.is-integer.php
Or if you want to check manually, then you can compare against the rounded down (floor) and rounded up (ceil) values:
if ($a==Floor($a) && $a==Ceil($a)){
// Whole Number
} else {
// Has decimal point value
}
You can try like below.
<?php
function is_decimal_exist( $value ) {
return is_numeric( $value ) && floor( $value ) != $value;
}
$my_value = "10.00";
if( is_decimal_exist ( $my_value ) ) {
echo ''; // Decimal Present, Do Not Print $my_value
}else{
echo $my_value; // Print $my_value
}
?>
Much easier. Just check if the integer of the number is equal == to the number:
if ((int)$c == $c) {
echo $c;
} else {
echo '';
}

Please help! How to express the cases in if clause?

I have string $a,$b,$c
I know if all of them not null express in this way:
if($a!="" && $b!="" && $c!="")
But if either 2 of them not null then go into the true caluse
if($a!="" && $b!="" && $c!=""){
** do the things here **
}else if(either 2 are not null){
**do another things here**
}
How to express it?
I would write a simple function like this to check:
function checkInput($var)
{
$nulls=0;
foreach($var as $val)
{
if(empty($val))
{
$nulls++;
}
}
return $nulls;
}
Then access it like this:
$inputs=array($a, $b, $c.... $z);
$nullCount=checkInput($inputs);
if($nullCount==0)
{
// All nulls
}
if($nullCount>2)
{
// More than 2 nulls
}
or for an one-off test, just pop the function into the actual if statement like this:
if(checkInput($inputs)>2)
{
// More than 2 nulls...
}
etc etc. You can then use the one function to check for any number of nulls in any number of variables without doing much work - not to mention change it without having to rewrite a long if statement if you want to modify it.
Other answers are good, but you can expand this to easily handle more variables:
$variables = array($a, $b, $c, $d, ....);
$howManyNulls = 0;
foreach($variables as $v){
if($v == ''){
$howManyNulls++;
}
}
if($howManyNulls == count($variables) - 2){
// do stuff
}
you can try this
if($a!="" && $b!="" && $c!="")
{
** do the things here **
}
else if(($a!="" && $b!="") || ($b!="" && $c!="") || ($a!="" && $c!=""))
{
**do another things here**
}
Try:
if($a!="" && $b!="" && $c!=""){
** do the things here **
}else if(($a!="" && $b!="") || ($a!="" && $c!="") || ($b!="" && $c!="")){
**do another things here**
}
$var[] = empty($a) ? 0:$a;
$var[] = empty($b) ? 0:$b;
$var[] = empty($c) ? 0:$c;
$varm = array_count_values($var);
if ($varm[0] === 0) {
//Code for when all aren't empty!
} elseif ($varm[0] === 1) {
//Code for when two aren't empty!
}
N.B; You may need to replace the 0 for a string/integer that will never crop up, if your variables are always strings or empty then 0 will do for this. The method for using bools within this would require more code.
$nullCount = 0
if($a!=""){ ++$nullCount; }
if($b!=""){ ++$nullCount; }
if($c!=""){ ++$nullCount; }
if($nullCount == 3){ // all are null
// do smth
}else if($nullCount == 2){ // only two are null
// do other
}
Just for fun, here's something potentially maintainable, should the list of arguments increase:
function countGoodValues(...$values) {
$count = 0;
foreach($values as $value) {
if($value != "") {
++$count;
}
}
return $count;
}
$goodValues = countGoodValues($a, $b, $c); // Or more... or less
if($goodValues == 3) {
// Do something here
}
else if($goodValues == 2) {
// And something else
}
Reference for the ... construct (examples #7 and #8 in particular) are available on php.net.
You can use double typecasting (to boolean, then to number) in conjunction with summing:
$count = (bool)$a + (bool)$b + (bool)$c;
if ($count == 3)
// ** do the things here **
else if ($count == 2)
//**do another things here**
There is also possible such solution:
<?php
$a= 'd';
$b = 'a';
$c = '';
$arr = array( (int) ($a!=""), (int) ($b!=""), (int) ($c!=""));
$occ = array_count_values($arr);
if ($occ[1] == 3) {
echo "first";
}
else if($occ[1] == 2) {
echo "second";
}
If you have 3 variables as in your example you can probably use simple comparisons, but if you have 4 or more variables you would get too big condition that couldn't be read.
if (($a!="") + ($b!="") + ($c!="") == 2) {
// two of the variables are not empty
}
The expression a!="" should return true (which is 1 as an integer) when the string is not empty. When you sum whether each of the strings meets this condition, you get the number of non-empty strings.
if (count(array_filter([$a, $b, $c])) >= 2) ...
This is true if at least two of the variables are truthy. That means $var == true is true, which may be slightly different than $var != "". If you require != "", write it as test:
if (count(array_filter([$a, $b, $c], function ($var) { return $var != ""; })) >= 2) ...
if($a!="" && $b!="" && $c!="") {
echo "All notnull";
} elseif(($a!="" && $b!="") || ($b!="" && $c!="") || ($a!="" && $c!="")) {
echo "Either 2 notnull";
}

PHP check for not > 0

Currently, the only way I can think of to reasonably check for this without bloated logic:
if ( $value > 0 ) {
// Okay
} else {
// Not Okay
}
Is there a better way?
The logical negation of "greater than 0" is "equal or smaller than 0".
if ($value <= 0) { ... }
It is a normal way to resolve problem. Also you can use this:
$value > 0 ? echo "Okay"; : echo "Not Okay";
Couple of ways you can go about this.
if (!($value > 0)) {
//If value not greater than 0
}
if ($value <= 0) {
//If value equal to or less than 0
}
Or if it is a simple assignment / return you can go and use short-if.
//Assign to variable
$variable = $value > 0 ? 'greater' : 'equal to or less';
//Return from function
return $value > 0 ? 'greater' : 'equal to or less';

Detecting negative numbers

I was wondering if there is any way to detect if a number is negative in PHP?
I have the following code:
$profitloss = $result->date_sold_price - $result->date_bought_price;
I need to find out if $profitloss is negative and if it is, I need to echo out that it is.
if ($profitloss < 0)
{
echo "The profitloss is negative";
}
Edit: I feel like this was too simple an answer for the rep so here's something that you may also find helpful.
In PHP we can find the absolute value of an integer by using the abs() function. For example if I were trying to work out the difference between two figures I could do this:
$turnover = 10000;
$overheads = 12500;
$difference = abs($turnover-$overheads);
echo "The Difference is ".$difference;
This would produce The Difference is 2500.
I believe this is what you were looking for:
class Expression {
protected $expression;
protected $result;
public function __construct($expression) {
$this->expression = $expression;
}
public function evaluate() {
$this->result = eval("return ".$this->expression.";");
return $this;
}
public function getResult() {
return $this->result;
}
}
class NegativeFinder {
protected $expressionObj;
public function __construct(Expression $expressionObj) {
$this->expressionObj = $expressionObj;
}
public function isItNegative() {
$result = $this->expressionObj->evaluate()->getResult();
if($this->hasMinusSign($result)) {
return true;
} else {
return false;
}
}
protected function hasMinusSign($value) {
return (substr(strval($value), 0, 1) == "-");
}
}
Usage:
$soldPrice = 1;
$boughtPrice = 2;
$negativeFinderObj = new NegativeFinder(new Expression("$soldPrice - $boughtPrice"));
echo ($negativeFinderObj->isItNegative()) ? "It is negative!" : "It is not negative :(";
Do however note that eval is a dangerous function, therefore use it only if you really, really need to find out if a number is negative.
:-)
if(x < 0)
if(abs(x) != x)
if(substr(strval(x), 0, 1) == "-")
You could check if $profitloss < 0
if ($profitloss < 0):
echo "Less than 0\n";
endif;
if ( $profitloss < 0 ) {
echo "negative";
};
Don't get me wrong, but you can do this way ;)
function nagitive_check($value){
if (isset($value)){
if (substr(strval($value), 0, 1) == "-"){
return 'It is negative<br>';
} else {
return 'It is not negative!<br>';
}
}
}
Output:
echo nagitive_check(-100); // It is negative
echo nagitive_check(200); // It is not negative!
echo nagitive_check(200-300); // It is negative
echo nagitive_check(200-300+1000); // It is not negative!
Just multiply the number by -1 and check if the result is positive.
You could use a ternary operator like this one, to make it a one liner.
echo ($profitloss < 0) ? 'false' : 'true';
I assume that the main idea is to find if number is negative and display it in correct format.
For those who use PHP5.3 might be interested in using Number Formatter Class - http://php.net/manual/en/class.numberformatter.php. This function, as well as range of other useful things, can format your number.
$profitLoss = 25000 - 55000;
$a= new \NumberFormatter("en-UK", \NumberFormatter::CURRENCY);
$a->formatCurrency($profitLoss, 'EUR');
// would display (€30,000.00)
Here also a reference to why brackets are used for negative numbers:
http://www.open.edu/openlearn/money-management/introduction-bookkeeping-and-accounting/content-section-1.7
Can be easily achieved with a ternary operator.
$is_negative = $profitloss < 0 ? true : false;
I wrote a Helper function for my Laravel project but can be used anywhere.
function isNegative($value){
if(isset($value)) {
if ((int)$value > 0) {
return false;
}
return (int)$value < 0 && substr(strval($value), 0, 1) === "-";
}
}

Categories