Range values to be calculated in PHP Loop - php

I need to calculate if avg is > 7.75 means Heavy else No.
What the concern is that.
Need to calculate that from $x to $y range of all numbers comes int.
But i was able to get one Avg only not sure what to do to get all numbers Average values and store in Array comes in that range.
function heavyDecC ($x,$y)
{
for($i=$x;$i<=$y;$i++)
{
$numb = $i;
$numleng = strlen((string)$i);
$int = 0;
for($j=0;$j<$numleng;$j++)
{
$int = $int + ($numb % 10);
$numb = (int)$numb / 10;
}
$avg = 0.00;
$avg = round($int/$numleng,2);
if($avg>7)
{
$isHeavy = "Yes";
}
else
{
$isHeavy = "No";
}
return $result[] = array($i,$avg,$isHeavy);
}
}

Here is a simple solution
<?php
$results = heavyDecC(2685, 5875);
// Display results like this
foreach ($results as $id){
echo "--------------------------<br/>";
foreach($id as $key => $val){
echo $key . " - " . $val . "<br />";
}
}
function heavyDecC ($x,$y) {
for($i=$x; $i<=$y; $i++){
$num = $x;
$isHeavy = "No";
$num_length = strlen((string)$num);
$array = array_map('intval', str_split($num));
$sum = array_sum($array);
$average = ($sum / $num_length);
if($average > 7){
$isHeavy = "Yes";
}else {
$isHeavy = "No";
}
$newdata = array (
'Number' => $num,
'average' => $average,
'is_heavy' => $isHeavy
);
$md_array[$i]= $newdata;
$x++;
}
return $md_array;
}
?>
Results like this
--------------------------
Number - 2991
average - 5.25
is_heavy - No
--------------------------
Number - 2992
average - 5.5
is_heavy - No
--------------------------
Number - 2993
average - 5.75
is_heavy - No
--------------------------
Number - 2994
average - 6
is_heavy - No
--------------------------
Number - 2995
average - 6.25
is_heavy - No
--------------------------
Number - 2996
average - 6.5
is_heavy - No
--------------------------
Number - 2997
average - 6.75
is_heavy - No
--------------------------
Number - 2998
average - 7
is_heavy - No
--------------------------
Number - 2999
average - 7.25
is_heavy - Yes
--------------------------

You have return value in every loop so it will only get last index values ! So you need to return outside of the loop ....
function heavyDecC ($x,$y)
{
$result = array();
for($i=$x;$i<=$y;$i++)
{
$numb = $i;
$numleng = strlen((string)$i);
$int = 0;
for($j=0;$j<$numleng;$j++)
{
$int = $int + ($numb % 10);
$numb = (int)$numb / 10;
}
$avg = 0.00;
$avg = round($int/$numleng,2);
if($avg>7)
{
$isHeavy = "Yes";
}
else
{
$isHeavy = "No";
}
$result[] = array($i,$avg,$isHeavy);
}
return $result; // return here outside of loop
}

Move your return outside of the for loop, like this:
function heavyDecC ($x,$y)
{
$result = array();
for($i=$x;$i<=$y;$i++)
{
$numb = $i;
$numleng = strlen((string)$i);
$int = 0;
for($j=0;$j<$numleng;$j++)
{
$int = $int + ($numb % 10);
$numb = (int)$numb / 10;
}
$avg = 0.00;
$avg = round($int/$numleng,2);
if($avg>7)
{
$isHeavy = "Yes";
}
else
{
$isHeavy = "No";
}
$result[] = array($i,$avg,$isHeavy);
}
return $result;
}

Related

How can I subtract a value gotten from the loop

This is my code
// $res[] has two values(75000, 30000)
// $_SESSION['requestedAmt'] = 35000
while ($row = $queryWithdrawalTable->fetch_assoc()) {
$res[] = $row['profit_amt'];
foreach ($res as $amt) {
if ($_SESSION['requestedAmt'] > $amt) {
$calc = $_SESSION['requestedAmt'] - $amt;
} else {
$calc = $amt - $_SESSION['requestedAmt'];
}
}
echo $calc; // outputs 5000 40000
}
What I actually want to achieve is
$a[] = (1500, 3000);
$b = 2500;
while(fetch the data) {
$res = $a - $b;
}
// output = 2000
I want the value in $b to subtract the first value in $a(1500) and use result gotten from the first calculation to subtract from the second value(3000). please note I'm new to programming so any suggestion will be accepted thanks guys.
I want to be able to assign a single user to pay multiple users. for example user1 has to pay $100 to user2($25), user3($50) and user4($25). I have user1 money in $_SESSION['requestedAmt'] while the other users in $row['profit_amt']
You are almost there, you only perform the calculation after you have all the value inside the $res array
while ($row = $queryWithdrawalTable->fetch_assoc()) {
$res[] = $row['profit_amt'];
}
$calc = $_SESSION['requestedAmt'];
foreach ($res as $amt) {
if ($_SESSION['requestedAmt'] > $amt) {
$calc = $calc - $amt;
} else {
$calc = $amt - $calc;
}
}
echo $calc;
Or you don't need the $res array at all, perform the calculation while fetching the rows:
$cals = $_SESSION['requestedAmt'];
while ($row = $queryWithdrawalTable->fetch_assoc()) {
if ($_SESSION['requestedAmt'] > $row['profit_amt']) {
$calc = $calc - $amt;
} else {
$calc = $amt - $calc;
}
}

How to convert word to number using my function?

I created this function to converting numbers to words. And how I can convert words to number using this my function:
Simple function code:
$array = array("1"=>"ЯК","2"=>"ДУ","3"=>"СЕ","4"=>"ЧОР","5"=>"ПАНҶ","6"=>"ШАШ","7"=>"ҲАФТ","8"=>"ХАШТ","9"=>"НӮҲ","0"=>"НОЛ","10"=>"ДАҲ","20"=>"БИСТ","30"=>"СИ","40"=>"ЧИЛ","50"=>"ПАНҶОҲ","60"=>"ШАСТ","70"=>"ҲАФТОД","80"=>"ХАШТОД","90"=>"НАВАД","100"=>"САД");
$n = "98"; // Input number to converting
if($n < 10 && $n > -1){
echo $array[$n];
}
if($n == 10 OR $n == 20 OR $n == 30 OR $n == 40 OR $n == 50 OR $n == 60 OR $n == 70 OR $n == 80 OR $n == 90 OR $n == 100){
echo $array[$n];
}
if(mb_strlen($n) == 2 && $n[1] != 0)
{
$d = $n[0]."0";
echo "$array[$d]У ".$array[$n[1]];
}
My function so far converts the number to one hundred. How can I now convert text to a number using the answer of my function?
So, as #WillParky93 assumed, your input has spaces between words.
<?php
mb_internal_encoding("UTF-8");//For testing purposes
$array = array("1"=>"ЯК","2"=>"ДУ","3"=>"СЕ","4"=>"ЧОР","5"=>"ПАНҶ","6"=>"ШАШ","7"=>"ҲАФТ","8"=>"ХАШТ","9"=>"НӮҲ","0"=>"НОЛ","10"=>"ДАҲ","20"=>"БИСТ","30"=>"СИ","40"=>"ЧИЛ","50"=>"ПАНҶОҲ","60"=>"ШАСТ","70"=>"ҲАФТОД","80"=>"ХАШТОД","90"=>"НАВАД","100"=>"САД");
$postfixes = array("3" => "ВУ");
$n = "98"; // Input number to converting
$res = "";
//I also optimized your conversion of numbers to words
if($n > 0 && ($n < 10 || $n%10 == 0))
{
$res = $array[$n];
}
if($n > 10 && $n < 100 && $n%10 != 0)
{
$d = intval(($n/10));
$sd = $n%10;
$ending = isset($postfixes[$d]) ? $postfixes[$d] : "У";
$res = ($array[$d * 10]).$ending." ".$array[$sd];
}
echo $res;
echo "\n<br/>";
$splitted = explode(" ", $res);
//According to your example, you use only numerals that less than 100
//So, to simplify your task(btw, according to Google, the language is tajik
//and I don't know the rules of building numerals in this language)
if(sizeof($splitted) == 1) {
echo array_search($splitted[0], $array);
}
else if(sizeof($splitted) == 2) {
$first = $splitted[0];
$first_length = mb_strlen($first);
if(mb_substr($first, $first_length - 2) == "ВУ")
{
$first = mb_substr($first, 0, $first_length - 2);
}
else
{
$first = mb_substr($splitted[0], 0, $first_length - 1);
}
$second = $splitted[1];
echo (array_search($first, $array) + array_search($second, $array));
}
You didn't specify the input specs but I took the assumption you want it with a space between the words.
//get our input=>"522"
$input = "ПАНҶ САД БИСТ ДУ";
//split it up
$split = explode(" ", $input);
//start out output
$c = 0;
//set history
$history = "";
//loop the words
foreach($split as &$s){
$res = search($s);
//If number is 9 or less, we are going to check if it's with a number
//bigger than or equal to 100, if it is. We multiply them together
//else, we just add them.
if((($res = search($s)) <=9) ){
//get the next number in the array
$next = next($split);
//if the number is >100. set $nextres
if( ($nextres = search($next)) >= 100){
//I.E. $c = 5 * 100 = 500
$c = $nextres * $res;
//set the history so we skip over it next run
$history = $next;
}else{
//Single digit on its own
$c += $res;
}
}elseif($s != $history){
$c += $res;
}
}
//output the result
echo $c;
function search($s){
global $array;
if(!$res = array_search($s, $array)){
//grab the string length
$max = strlen($s);
//remove one character at a time until we find a match
for($i=0;$i<$max; $i++ ){
if($res = array_search(mb_substr($s, 0, -$i),$array)){
//stop the loop
$i = $max;
}
}
}
return $res;
}
Output is 522.

Decimals For negative PHP values

I am writing a bit of php code to output a random value
$max_mal = (3 - $oray);
$oray = 1;
$max = 100;
$total = 0;
for ($i = 0; $i < $max_mal; $i++){
$goli = mt_rand(3, 8);
$total += $goli;
$golis[] = $goli;
}
and for each loop goes here
foreach($golis as &$goli) {
$goli = floor(($goli / $total) * $max);
if ($goli == 0) {
$goli = 1;
}
}
$result = array_pad($golis, 3, -1);
shuffle($result);
$myresult = $result[0];
I am looking to get decimal values upto 5 numbers, but once a negative value comes it results out as 0.000-1 instead of -0.00001
$myresultb = str_pad($mario, 5, '0', STR_PAD_LEFT);
$myresultf = '0.'.$myresultb.'<br/>';
$total_score = 300;
echo $myresultf;
Secondly I am new to php learning so am I doing this PHP correct or it needs improvement
I have a div to show total score like this
<div id="total_score"></div>
and another div to show current score which value comes as echo $myresultf;
<div id="current_score"></div>
I want to update total score in real time with jquery wheneven button is clicked and <?php echo $myresultf ?> is refreshed in real time also
$("#play").click(function() {
var currentscore = $("#current_score").val();
var totalscore = $("#total_score").val();
how to do this.....
});
Try this:
$max = 100;
$oray = 1;
$max_mal = (3 - $oray);
$total = 0;
for ($i = 0; $i < $max_mal; $i++){
$goli = mt_rand(3, 8);
$total += $goli;
$golis[] = $goli;
}
foreach($golis as &$goli) {
$goli = floor(($goli / $total) * $max);
if ($goli == 0) {
$goli = 1;
}
}
$result = array_pad($golis, 3, -1);
shuffle($result);
$myresult = $result[0];
$negative_var=false;
if($myresult < 0)
{
$negative_var=true;
$myresult = 0-$myresult;
}
$myresultb = str_pad($myresult, 5, '0', STR_PAD_LEFT);
$myresultf = '0.'.$myresultb.'<br/>';
if($negative_var)
$myresultf="-".$myresultf;
$total_score = 300;
echo $myresultf;
simple use as follow:
$myresultb =str_replace('-','',$myresultb);
if($myresult == -1) {
$myresultf = '-0.'.$myresultb.'<br/>';
}
else {
$myresultf = '0.' . $myresultb . '<br/>';
}

Check if a variable is in POWER base + PHP

I want to check if an input variable is in POWER base.
For example :
Input : 25 ;//yes in power pow(5,2)
Input : 26 ;//no not in power
I made a code but its time taking
$var = 25;
$half = round($var / 2);
for($x = 0; $x <= $half; $x++){
for($y = 0; $y <= $half; $y++){
if(pow($x, $y) === $var){
$output = "1";
}
}
}
if(!$output){
echo "0";
}else{
echo "1";
}
You can use sqrt which will return square root of given number, then just check if the returned value is in decimal or not.
$var = 25;
$sqrt = sqrt($var);
if($sqrt !== floor( $sqrt )) {
echo 'no power';
} else {
echo 'power';
}

PHP generate football schedule

I have 38 days and 20 clubs (EPL).
How can I generate not repeated matches for this clubs in this days (schedule)?
For example:
Day 1:
club1 - club2
club3 - club4
...
club19 - club 20
Day 2:
club1 - club3
club2 - club4
...
club20 - club18
Each club plays with other two games (home and away). Respectively do not play with himself.
My thinks:
$clubs1 = array();
$clubs2 = array();
$days = range(1, 38);
$calendar = array();
$pars = array();
$rows = Yii::app()->db->createCommand()
->select('id')
->from('clubs')
->queryAll();
foreach ($rows as $item) {
$clubs1[] = $item['id'];
$clubs2[] = $item['id'];
}
shuffle($clubs1);
shuffle($clubs2);
$total = (count($clubs1) * 2) - 2;
for ($j = 1; $j <= $total; $j ++) {
$day = $days[$j];
for ($i = 0; $i < count($clubs1); $i++) {
WHAT I SHOULD DO IN THIS BODY?
}
}
You need only one clubs array
1) remove $clubs2
2) rename $clubs1 to $clubs
3) remove whole for structure
//for testing: $clubs=array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
$countofteams=count($clubs);
$c=1;
for($j=0;$j<2;$j++) //home/away
for($i=1;$i<$countofteams;$i++){ //move teams
echo '----DAY '.$c++.'----<br>';
for($a=0;$a<$countofteams;$a++) //all teams are playing
echo 'Match '.$clubs[$a].' vs '.$clubs[($a+$i)%$countofteams].'<br>';
}
$team = array();
$pars = array();
$rows = Yii::app()->db->createCommand()
->select('id')
->from('clubs')
->queryAll();
foreach ($rows as $k => $item) {
$team[$k+1] = $item['id'];
}
$all_team = count($team);
$k = $all_team/2;
$days = range(7, 100, 2); // first halh of season
$days2 = range(55, 100, 2); // second half
// 1 tour
for ($i=1; $i <= $k; $i++) {
$pars[] = $days[0].'|'.$team[$i].'|'.$team[($all_team-$i+1)];
$pars[] = $days2[0].'|'.$team[($all_team-$i+1)].'|'.$team[$i];
}
// Next tours
for($i=2; $i<$all_team; $i++)
{
$team2 = $team[2];
for($y=2;$y<$all_team;$y++)
{
$team[$y] = $team[$y+1];
}
$team[$all_team] = $team2;
for($j=1;$j<=$k;$j++)
{
$pars[] = $days[$i - 1].'|'.$team[$j].'|'.$team[($all_team-$j+1)];
$pars[] = $days2[$i - 1].'|'.$team[($all_team-$j+1)].'|'.$team[$j];
}
}
Here's my solution, replace the $clubs array with your result set of club IDs from database. The only slight inaccuracy with real-world EPL is that the second half of the season will mirror the first half exactly.
See if this adaption of http://board.phpbuilder.com/showthread.php?10300945-Round-Robin-Generator is any better :) - just for first half of the season.
$clubs = array(
'che', 'swa', 'ast', 'manc', 'liv', 'tot', 'ars', 'sot', 'hul', 'stok', 'wham', 'qpr', 'sun', 'mutd', 'lei', 'new', 'eve', 'wba', 'cry', 'bur',
);
shuffle($clubs);
$num_players = count($clubs) - 1;
// Set the return value
$ret = '';
// Generate the pairings for each round.
for ($round = 0; $round < $num_players; $round++) {
$ret .= '<h3>' . ($round + 1) . '</h3>';
$players_done = array();
// Pair each player except the last.
for ($player = 1; $player < $num_players; $player++) {
if (!in_array($player, $players_done)) {
// Select opponent.
$opponent = $round - $player;
$opponent += ($opponent < 0) ? $num_players : 1;
$playerName = $clubs[$player];
$opponentName = $clubs[$opponent];
// Ensure opponent is not the current player.
if ($opponent != $player) {
// Choose colours.
if (($player + $opponent) % 2 == 0 xor $player < $opponent) {
// Player plays white.
$ret .= "$playerName - $opponentName $br";
} else {
// Player plays black.
$ret .= "$opponentName - $playerName $br";
}
// This pair of players are done for this round.
$players_done[] = $player;
$players_done[] = $opponent;
}
}
}
// Pair the last player.
if ($round % 2 == 0) {
$playerName = $clubs[$num_players];
$opponent = ($round + $num_players) / 2;
$opponentName = $clubs[$opponent];
// Last player plays white.
$ret .= "$playerName - $opponentName $br";
} else {
$opponent = ($round + 1) / 2;
// Last player plays black.
$ret .= "$opponentName - $playerName $br";
}
}
echo $ret;

Categories