I have the need to count the number of integers which i am adding/substracting from equation.
Lets say I have a switch statement like that:
switch($_POST['dni']){
case 2:
$sum1 = $day1;
$sum2 = $day2;
break;
case 3:
$sum1 = $day1 + $day2;
$sum2 = $day3;
break;
case 4:
$sum1 = $day1 + $day2;
$sum2 = $day3 + $day4;
break;
case 5:
$sum1 = $day1 + $day2 + $day3;
$sum2 = $day4 + $day5;
break;
case 6:
$sum1 = $day1 + $day2 + $day3;
$sum2 = $day4 + $day5 + $day6;
break;
case 7:
$sum1 = $day1 + $day2 + $day3 + $day4;
$sum2 = $day5 + $day6 + $day7;
break;
case 8:
$sum1 = $day1 + $day2 + $day3 + $day4;
$sum2 = $day5 + $day6 + $day7 + $day8;
break;
And I have selected $_POST['dni'] to be 7, can I count the number of integers in $sum1 equation?
The things I have tried so far:
explode($sum1, '+') - returns the sum of the equation in array...
count($sum1) - returns 1, because it is counting again the sum of
equation...
Are you thinking of something like this? But without a better example this is all I got for you.
$day1 = 1;
$day2 = 2;
$day3 = 3;
$day4 = 4;
$array = array(
'0' => $day1,
'1' => $day2,
'2' => $day3,
'3' => $day4
);
$sum = array_sum($array);
echo 'Sum: = ' . $sum . '<br>'; //Outputs 10
echo '# of Integers: = ' . count($array); //Outputs 4
So I think it's a bad practice to use switch statement and re-did your code by -infer- method and resolved the issue, I hope it helps:
<?php
// In my example I have to declare the days and sums variables
// but I'm assuming you have them declared in your code already…
$dni = 8; // Or $_POST['dni'];
$day1 = 3;
$day2 = 4;
$day3 = 6;
$day4 = 8;
$day5 = 2;
$day6 = 5;
$day7 = 3;
$day8 = 10;
$day9 = 15;
$sum1 = $sum2 = 0;
// Here by what I saw in your code, can be simplified with basic arithmetic.
// First I divide $dni by 2, if it's an odd number it'll result in a float number.
// By using ceil we round it to the closest even number.
$primary_sum = ceil($dni / 2);
// Then just subtract the $primary_sum from $dni
// and you'll have your $secondary_sum.
$secondary_sum = $dni - $primary_sum;
// Here what I did is make an array with $dni number of keys.
// (Serves as your switch statement).
foreach (array_fill(1, $dni, '') as $day_number => $x)
{
// Follow the logic.
if ($day_number <= $primary_sum)
{
// This is a little trick but works like a charm.
$sum1 += ${"day{$day_number}"}; // It's basically $day1... and on.
}
else if ($day_number > $primary_sum)
{
// This is a little trick but works like a charm.
$sum2 += ${"day{$day_number}"};
}
}
// Number of integers in first sum (sum1)
var_dump($primary_sum);
// Number of integers in second sum (sum2)
var_dump($secondary_sum);
// The total sum of sum1 (pretty obvious).
var_dump($sum1);
// The total sum of sum2 (pretty obvious).
var_dump($sum2);
You can paste that code in phpsandbox and see it in action.
Related
I need to validate that an inputted number is a valid number based on my stepping rules and round up to the nearest valid number if not. These numbers will change but one example would be:
$min = 0.25;
$step = 0.1
$qty = 0.75 // user input
so these would be valid inputs:
0.75
0.85
0.95
But these should round:
0.76 (to 0.85)
0.80 (to 0.85)
I thought I could use modulus somehow but not getting the calculation correct.
if (($qty % min) / $step == 0)) {
echo "good";
}
I've tried some variations of math that are likely very wrong
$step = 0.1;
$min = 0.25;
$qty = .85;
$h = ($qty / $min) / $step;
echo $h;
$j = mround($qty, $min-$step);
echo $j;
function mround($num, $parts) {
if ($parts <= 0) { $parts = 1; }
$res = $num * (1/$parts);
$res = round($res);
return $res /(1/$parts);
}
I think you can use fmod to do this.
$new = $original + ($step - fmod($original - $minimum, $step));
Example on 3v4l.org
I have a wheel of fortune that spins, and has probability set for winning each prize that adds up to 100%. Once the quantity of a prize is met, ie, all of that prize is gone from stock, it sets the probability to 0 so you can't win it again. My problem then, is that the other values don't add up to 100. They always have to add up to 100 otherwise the wheel doesn't work.
I've got to the point of dividing all of the values by the total, rounding to two decimals and then adding them together, but i get 99 instead of 100. I've tried a few other ways of doing it and can never get to 100.
edit: My main problem seems to be that there is a 0.01% chance of winning 2 of the prizes. Dividing them by the total drops them to 0.000234234% or something similar, so when i multiply that by 100 then round that up to 2 decimals i'm getting 0.00% - but i can't think of any other way around it...
$jsonString = file_get_contents('wp-content/themes/supertheme/wheel_data.json');
$data = json_decode($jsonString, true);
echo '<pre>';
//print_r($data['segmentValuesArray'][0]['probability']);
echo '</pre>';
if ($prize1 <= 5){
$prize1before = $data['segmentValuesArray'][0]['probability'];
$data['segmentValuesArray'][0]['probability'] = 0;
}
if ($prize2 >= 5){
$data['segmentValuesArray'][1]['probability'] = 0;
}
if ($prize3 >= 300){
$data['segmentValuesArray'][2]['probability'] = 0;
}
if ($prize4 >= 500){
$data['segmentValuesArray'][3]['probability'] = 0;
}
if ($prize5 >= 10){
$data['segmentValuesArray'][4]['probability'] = 0;
}
$prize1total = $data['segmentValuesArray'][0]['probability'];
$prize2total = $data['segmentValuesArray'][1]['probability'];
$prize3total = $data['segmentValuesArray'][2]['probability'];
$prize4total = $data['segmentValuesArray'][3]['probability'];
$prize5total = $data['segmentValuesArray'][4]['probability'];
$total = $prize1total + $prize2total + $prize3total + $prize4total + $prize5total;
echo'<pre>';
print_r($total);
echo'<pre>';
$a = 0;
foreach($data['segmentValuesArray'] as $prize_array){
if($prize_array['probability'] > 0){
$a++;
}
}
$integer = $prize1before / $a;
$divided1 = $prize1total / $total;
$rounded1 = number_format((float)$divided1, 2, '.', '');
$full1 = $rounded1 * 100;
$divided2 = $prize2total / $total;
$rounded2 = number_format((float)$divided2, 2, '.', '');
$full2 = $rounded2 * 100 + $integer;
$divided3 = $prize3total / $total;
$rounded3 = number_format((float)$divided3, 2, '.', '');
$full3 = $rounded3 * 100 + $integer;
$divided4 = $prize4total / $total;
$rounded4 = number_format((float)$divided4, 2, '.', '');
$full4 = $rounded4 * 100 + $integer;
$divided5 = $prize5total / $total;
$rounded5 = number_format((float)$divided5, 2, '.', '');
$full5 = $rounded5 * 100 + $integer;
$newtotal = $full1 + $full2 + $full3 + $full4 + $full5;
echo'<pre>';
print_r($newtotal);
echo'<pre>';
$newJsonString = json_encode($data, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
file_put_contents('wp-content/themes/supertheme/wheel_data.json', $newJsonString);
$Grade and $Remark is always evaluated at the last value of $total (i.e where ($check_ss=="Ss")) but I want it to get value at every instance of the if conditions. How do I do
Eg at first condition it gets value of grade and remark same for subsequent conditions
or do i haveto include the switch statement inside each if statement
//Logic and Calc
if ($check_en=="En"){
$ot_en = $ent1 + $ent2 + $ent3 + $ent4 + $enexm;
$total = $ot_en;
}
if ($check_ms=="Ms"){
$ot_ms = $mst1 + $mst2 + $mst3 + $mst4 + $msexm;
$total = $ot_ms;
}
if ($check_ss=="Ss"){
$ot_ss = $sst1 + $sst2 + $sst3 + $sst4 + $ssexm;
$total = $ot_ss;
}
$ot= $ot_ms + $ot_ss + $ot_en;
switch ($total) {
case $total > 70:
$grade = "A";
$remark = "Excellent";
break;
case $total >= 60 && $total <= 69:
$grade = "B";
$remark = "Very Good";
break;
case $total >= 50 && $total <= 59:
$grade = "C";
$remark = "Good";
break;
case $total >= 45 && $total <= 49:
$grade = "D";
$remark = "Pass";
break;
case $total >= 40 && $total <= 44:
$grade = "E";
$remark = "Poor";
break;
case $total <= 39:
$grade = "F";
$remark = "Fail";
break;
}
if ($total == 0) {
$grade = "F";
$remark = "Fail";
Make your switch statement into a function and also use an array to hold the grade and remark data. Something like this:
function checkGrade($total)
{
$ret = array();
switch ($total) {
case $total > 70:
$ret['grade'] = "A";
$ret['remark'] = "Excellent";
break;
case $total >= 60 && $total <= 69:
$ret['grade'] = "B";
$ret['remark'] = "Very Good";
break;
case $total >= 50 && $total <= 59:
$ret['grade'] = "C";
$ret['remark'] = "Good";
break;
case $total >= 45 && $total <= 49:
$ret['grade'] = "D";
$ret['remark'] = "Pass";
break;
case $total >= 40 && $total <= 44:
$ret['grade'] = "E";
$ret['remark'] = "Poor";
break;
case $total <= 39:
$ret['grade'] = "F";
$ret['remark'] = "Fail";
break;
}
return $ret;
}
Now you can easily use this within your if() conditions, and get back the grade at each point.
$gradesAlongTheWay = array();
if ($check_en=="En"){
$ot_en = $ent1 + $ent2 + $ent3 + $ent4 + $enexm;
$total = $ot_en;
$gradesAlongTheWay['En'] = checkGrade($total);
}
if ($check_ms=="Ms"){
$ot_ms = $mst1 + $mst2 + $mst3 + $mst4 + $msexm;
$total = $ot_ms;
$gradesAlongTheWay['Ms'] = checkGrade($total);
}
if ($check_ss=="Ss"){
$ot_ss = $sst1 + $sst2 + $sst3 + $sst4 + $ssexm;
$total = $ot_ss;
$gradesAlongTheWay['Ss'] = checkGrade($total);
}
Then you can dump out the gradesAlongTheWay() to find out what the grade was at each specific point. This will be a multi-dimensional array with 3 primary indices:
Array(
'En' => array(
'grade' => 'Some Letter',
'remark' => 'Some notation'
),
'Ms' => array(
'grade' => 'Some Letter',
'remark' => 'Some notation'
),
'Ss' => array(
'grade' => 'Some Letter',
'remark' => 'Some notation'
)
)
Now we can easily access the grades at each point by index and their grade, thussly:
echo $gradesAlongTheWay['En']['grade']; // produces the letter from this check
echo $gradesAlongTheWay['Ss']['remark']; //produces the notation/message from this check
You can also just loop over them.
foreach($gradesAlongTheWay as $type => $gradeArray)
{
echo 'For Check '. $type .' you received an: '. $gradeArray['grade'] .'. '. $gradeArray['remark'];
}
Edit
You're getting SQL errors because of the ' apostrophe in your PHP code being injected into your MySQL code. Instead, you need to use mysqli prepared statements.
$stmt = mysqli_prepare($conn, "INSERT INTO records VALUES (NULL, '?', 'English Language', '?', '?', '?', '?', '?', '?', ?, 'Poor'");
mysqli_stmt_bind_param($stmt, "ssssssss", $sid, $ent1, $ent2, $ent3, $ent4, $enexm, $ot_en, $gradesAlongTheWay['En']['grade']);
mysqli_stmt_execute($stmt);
This will make sure your data is correctly sanitized.
Please read more into mysqli prepared statements here
I'm trying to do an activity where I need do put a number in cm, and the program has to return it with km, m, and cm.
An example: 270004 cm = 2km, 700m, 4cm // 100cm = 0km, 1m, 0cm.
I have done this code, but, sometimes I get negative numbers, and sometimes I get strange numbers.
Maybe is why I use the PHP_ROUND_HALF_UP??
What can I do to solve it?
//I have an HTML form to introduce the number value
$num = 123456789;
$km = $num/1000;
$km = round($km, 0, PHP_ROUND_HALF_UP);
echo "km: ".$km."<br>";
$subtraction = ($km * 1000) - $num;
$m = $subtraction / 100;
$m = round($m, 0, PHP_ROUND_HALF_UP);
echo "m: ".$m."<br>";
$subtraction2 = ($m * 100) - $subtraction;
$cm = $subtraction2;
echo "cm: ".$cm."<br>";
Honestly, your code seems to be a bit over complicated :P Ever heard of modulo division? Comes in handy in here!
<?php
$x = 123456789323; // centimeters
$km = floor($x / 100000); // amount of "full" kilometers
$rkm = $x % 100000; // rest
$m = floor($rkm / 100); // amount of "full" meters"
$cm = $rkm % 100; // rest
echo $x . ' cm = ' . $km . ' kilometers ' . $m . ' meters and ' . $cm . 'centimeters' . PHP_EOL;
$cm = 234459891345;
echo sprintf('km: %02d m: %02d cm: %02d', ($cm/100000),($cm/100%100), $cm%100);
What I need is putting this array in a loop, but I can't get it to work because week is 1 - 9 and the key is 0 - 8. So i getting a error with a undefined offset i know why the does that but I don't know how to do this properly.
Before people ask me why not just change week1 to week0 and start counting from there. I can't because I did a calculating that is based on 1 - 52 and it will mess up my calculating if I start on 0 - 51
$totaal_vruchtzetting_week[10] = $totaal["week1"][0] + // = 0.46
$totaal["week2"][1] + // = 2.87
$totaal["week3"][2] + // = 4.97
$totaal["week4"][3] + // = 4.35
$totaal["week5"][4] + // = 3.02
$totaal["week6"][5] + // = 2.03
$totaal["week7"][6] + // = 1.41
$totaal["week8"][7] + // = 1.12
$totaal["week9"][8]; // = 1.13
// Should be total 21,36
Edit:
This is my loop I got until now but it gives me the wrong answer plus 2 errors
for($week = 1; $week < 9; $week++)
{
for($sw = 0; $sw <= 8; $sw++)
{
$totaal_vruchtzetting_week[10] += $totaal["week".$week][$sw];
}
}
echo $totaal_vruchtzetting_week[10]; // Outputs 170.89
$i=1;
$totaal_vruchtzetting_week[10]=0;
foreach($totaal as $total)
{
$totaal_vruchtzetting_week[10]+=$total["week$i"][$i-1];
$i++;
}
echo $totaal_vruchtzetting_week[10];
You should sum with this this loop
$i = 1;
$result = 0;
for ($i = 1; $i <= 9; $i++) {
if (isset($totaal['week' . $i]) && isset($totaal['week' . $i][$i - 1])) {
$result += floatval($totaal['week' . $i][$i - 1]);
}
}
$totaal_vruchtzetting_week[10] = $result;
$sum = 0;
foreach(array_values($totaal) as $index=>$item)
$sum += reset($item);
echo $sum; // 21.36
$totaal_vruchtzetting_week[10] = $sum;
Demo
Not sure if I got your question, but did you consider foreach? It iterates over every array regardless of the keys.