php multiple if else statement how to combine into one function? - php

i got 7 if else statement, may I know how i can compile it into one function file? so I just trigger the function rather a long and messy code.
below are my codes:
<?php
$r1a = $_POST['rowone'];
if ($r1a<7) {
$r2a=$r1a+1;
} else {
$r2a=$r1a+1-7;
}
if ($r2a<7) {
$r3a=$r2a+1;
} else {
$r3a=$r2a+1-7;
}
if ($r3a<7) {
$r4a=$r3a+1;
} else {
$r4a=$r3a+1-7;
}
if ($r4a<7) {
$r5a=$r4a+1;
} else {
$r5a=$r4a+1-7;
}
if ($r5a<7) {
$r6a=$r5a+1;
} else {
$r6a=$r5a+1-7;
}
if ($r6a<7) {
$r7a=$r6a+1;
} else {
$r7a=$r6a+1-7;
}
?>
the second problem I have is adding all together, there are 7 vertical row that have 3 value and another 5 row that have 2 value to add. I found out my code over here if there is a total value of 12 it will show 0 because of my code -12. Is there anyone I wan alter the code if the value is 12, the result will +1-12?
Thanks!
<?php
$r4a = $r1a+$r2a+$r3a;
if ($r4a<12) {
$r4a=$r4a;
} else {
$r4a=$r4a-12;
}
$r4b = $r1b+$r2b+$r3b;
if ($r4b<12) {
$r4b=$r4b;
} else {
$r4b=$r4b-12;
}
$r4c = $r1c+$r2c+$r3c;
if ($r4c<12) {
$r4c=$r4c;
} else {
$r4c=$r4c-12;
}
$r4d = $r1d+$r2d+$r3d;
if ($r4d<12) {
$r4d=$r4d;
} else {
$r4d=$r4d-12;
}
$r4e = $r1e+$r2e+$r3e;
if ($r4e<12) {
$r4e=$r4e;
} else {
$r4e=$r4e-12;
}
$r4f = $r1f+$r2f+$r3f;
if ($r4f<12) {
$r4f=$r4f;
} else {
$r4f=$r4f-12;
}
$r4g = $r1g+$r2g+$r3g;
if ($r4g<12) {
$r4g=$r4g;
} else {
$r4g=$r4g-12;
}
$r4h = $r2h+$r3h;
if ($r4h<12) {
$r4h=$r4h;
} else {
$r4h=$r4h-12;
}
$r4i = $r2i+$r3i;
if ($r4i<12) {
$r4i=$r4i;
} else {
$r4i=$r4i-12;
}
$r4j = $r2j+$r3j;
if ($r4j<12) {
$r4j=$r4j;
} else {
$r4j=$r4j-12;
}
$r4k = $r2k+$r3k;
if ($r4k<12) {
$r4k=$r4k;
} else {
$r4k=$r4k-12;
}
$r4l = $r2l+$r3l;
if ($r4l<12) {
$r4l=$r4l;
} else {
$r4l=$r4l-12;
}
?>

I don't think you need the if's at all. Modulo operations should solve it for you.
function inc($a) {
return ($a % 7)+1;
}
$r1a = $_POST['rowone'];
$r2a = inc($r1a);
$r3a = inc($r2a);
$r4a = inc($r3a);
$r5a = inc($r4a);
$r6a = inc($r5a);
$r7a = inc($r6a);
Code hasn't been tested, but you get the general idea.
Another alternative:
$v = $_POST['rowone'];
$arr = array(1, 2, 3, 4, 5, 6, 7);
$b = array_slice($arr, 0, $v-1);
$arr = array_slice($arr, $v-1);
$arr = array_merge($arr, $b);
print_r($arr);
Answer to your second question where I have only made 0 into 1 and kept the rest as it were(To clearify, if the input to mod12 e.g $r1a+$r2a+$r3a is a multiple of 12 it will return 1, in other cases it will return a standard modulo 12 e.g 13 will become 1):
function mod12($a) {
$m = $a % 12;
if ($m == 0) {
return 1;
}else {
return $m;
}
}
$r4a = mod12($r1a+$r2a+$r3a);
$r4b = mod12($r1b+$r2b+$r3b);
$r4c = mod12($r1c+$r2c+$r3c);
$r4d = mod12($r1d+$r2d+$r3d);
$r4e = mod12($r1e+$r2e+$r3e);
$r4f = mod12($r1f+$r2f+$r3f);
$r4g = mod12($r1g+$r2g+$r3g);
$r4h = mod12($r2h+$r3h);
$r4i = mod12($r2i+$r3i);
$r4j = mod12($r2j+$r3j);
$r4k = mod12($r2k+$r3k);
$r4l = mod12($r2l+$r3l);

If I understood well what you try to achieve, this should work:
$r1a = $_POST['rowone'];
for ( $i = 1; $i < 7; $i++ ){
$cur = 'r'.$i.'a';
$next = 'r'.($i+1).'a';
$$next = $$cur < 7 ? $$cur+1 : $$cur+1-7
}

Related

Run function when if statement is true (For Loop)

I have one issue that I can't solve. So I have for loop.
So here is little code:
for ($i=0;$i<3;$i++) {
$int = $i + 1;
if($sms->mobio_check($servID,$request->input("code$int"))) {
continue;
$cart->success($product->id,$product->server->name);
} else {
return redirect()->to(route('mcCheckoutFailed'))->withErrors(['codeError'=>__('messages.invalidCode',['input'=>$int])]);
}
}
I want if three ifs return true to run function $sms->success();.
What is wrong here?
You could rely on the fact that if the loop finished, then it's OK, any failures will cause the return in the loop to exit...
for ($i=0;$i<3;$i++) {
$int = $i + 1;
if( ! $sms->mobio_check($servID,$request->input("code$int"))) {
return redirect()->to(route('mcCheckoutFailed'))->withErrors(['codeError'=>__('messages.invalidCode',['input'=>$int])]);
}
}
$cart->success($product->id,$product->server->name);
You can do it like this:
$success = true;
for ($i=0;$i<3;$i++) {
$int = $i + 1;
if($success = $success || $sms->mobio_check($servID,$request->input("code$int"))) {
continue;
$cart->success($product->id,$product->server->name);
} else {
return redirect()->to(route('mcCheckoutFailed'))->withErrors(['codeError'=>__('messages.invalidCode',['input'=>$int])]);
}
}
if ($success) $sms->success();
you can try this
$count = 0;
for ($i=0;$i<3;$i++) {
$int = $i + 1;
if($sms->mobio_check($servID,$request->input("code$int"))) {
$count++;
} else {
return redirect()->to(route('mcCheckoutFailed'))->withErrors(['codeError'=>__('messages.invalidCode',['input'=>$int])]);
}
}
if($count == 3)
$cart->success($product->id,$product->server->name);

Detecting a cycle in an array PHP

I'm running a simple script which puts an integer through the formula of the Collatz conjecture and adds the output of each step into an array.
I want to use a function to detect if there's a cycle in the array, using Floyd's algorithm. And though I feel like I'm not doing a bad job, I don't seem to get it right. At this moment I'm getting the error Trying to get property 'next' of non-object in C:\xampp\htdocs\educom\week3\functions.php on line 12
See my code below. Any feedback is greatly appreciated!
include("functions.php");
$n = $_POST['number'];
$step = 0;
$reeks1 = array();
$cycle = 0;
echo "Your entry is: ". $n ."<br><br>";
while($n!==1 && $cycle==0){
$cycle = detect_cycle(array($reeks1));
if($n % 2 == 0){
$n = $n / 2;
array_push($reeks1, "$n");
$step++;
echo $step .": ". $n ."<br>";
}else{
$n = ($n * 3) + 1;
array_push($reeks1, "$n");
$step++;
echo $step .": ". $n ."<br>";
}
}
functions.php:
function detect_cycle($node){
if ($node==NULL){
return FALSE;
}
$turtle = $node;
$rabbit = $node->next;
while($rabbit != NULL){
if($rabbit === $turtle){
return TRUE;
}elseif($rabbit->next == NULL){
return FALSE;
}else{
$turtle = $turtle->next;
$rabbit = $rabbit->next->next;
}
}
return FALSE;
}
Check this out. IMPORTANT I don't know is this according to your theory. but it won't give you errors if you use like this.
function detect_cycle($node){
if ($node==NULL){
return FALSE;
}
$turtle = $node;
$rabbit = $node[0];
while($rabbit != NULL){
if($rabbit === $turtle){
return TRUE;
}elseif($rabbit[0] == NULL){
return FALSE;
}else{
$turtle = $turtle[0]; // use the number of the element key starting from 0
$rabbit = $rabbit[0][1];
}
}
return FALSE;
}

Foreach code working - but asking for optimalization

The below code works and does output exactly what i want. I made a foreach loop getting the values of a specific field ($CustomFields...) which is part of a framework variable. Then is only counts that field when the condition is "group".
After that i want to het the average price of all fields / count.
// ########### Get average hourly rate for group classes
$itemsperhour = array();
$countperhour = 0;
foreach($listings as $listing) {
if ($CustomFields->fieldValue('jr_typeoflesson',$listing,false,false) == 'group') {
$itemsperhour[] = $CustomFields->field('jr_hourlyrateus',$listing,false,false);
$countperhour = $countperhour + 1;
}
}
//print_r($items);
if ($countperhour > 0) {
$totalperhour = array_sum($itemsperhour);
$averageperhour =($totalperhour / $countperhour);
echo round($averageperhour,2);
} else {
echo "No data";
}
unset ($averageperhour);
As said, the snippet works. But may I ask how other people would write such a script related to optimise such a piece of code (for speed and readability?
PHP 5.6+
Jasper
Below is one way of optimizing:
$totalperhour = 0;
$countperhour = 0;
foreach($listings as $listing) {
if ($CustomFields->fieldValue('jr_typeoflesson',$listing,false,false) == 'group') {
$totalperhour += $CustomFields->field('jr_hourlyrateus',$listing,false,false);
$countperhour = $countperhour + 1;
}
}
if($countperhour > 0) {
$averageperhour =($totalperhour / $countperhour);
echo round($averageperhour,2);
$averageperhour = '';
} else {
echo "No data";
}
I would suppose to use array_reduce function for getting the average:
$averageperhour = array_reduce($listings, function($average, $listing) use (&$CustomFields)
{
static $sum = 0;
static $counter = 0;
if ($CustomFields->fieldValue('jr_typeoflesson', $listing, false, false) == 'group') {
$sum += $CustomFields->field('jr_hourlyrateus', $listing, false, false);
$counter ++;
$average = round(($sum / $counter), 2);
}
return $average;
}, 'No data');
echo $averageperhour;
Not sure about speed improvement (needs testing), but this variant seems to me like more readable.
How about this?
$itemsPerHour = [];
foreach($listings as $listing) {
if ($CustomFields->fieldValue('jr_typeoflesson', $listing, false, false) !== 'group') {
continue;
}
$itemsPerHour[] = $CustomFields->field('jr_hourlyrateus', $listing, false, false);
}
$countPerHour = count($itemsPerHour);
if ($countPerHour > 0) {
$averagePerHour = array_sum($itemsPerHour) / $countPerHour;
echo round($averagePerHour,2);
} else {
echo "No data";
}

Is there anyway to repeat the biggest segment of continuous segment of repeat using php?

I want to put the input like "RKKRRRRK" and try to get the output like largest continuous segment.. Suppose my input may be "RKKKR" then my program will display 'KKK' is the largest continuous segment.. and then it also display the count is 3..
I've already write the code for counting 'R' values.. now i want this program also... need help anyone help me.. thanks in advance.
Here the code:-
<?php
function numberOfR($string1)
{
for($i=0;$i <strlen($string1);$i++)
{
if($string1[$i]!='K')
{
$count++;
}
}
return $count;
}
$return_value= numberOfR("RKKRK");
echo "R's count is:";
echo $return_value;
?>
<?php
function getLongetSegment($string) {
$currentSegmentChar='';
$currentSegment="";
$biggestSegment="";
$current_length=0;
$biggest_length=0;
for($i=0;$i<strlen($string);$i++) {
$char = $string[$i];
if($char != $currentSegmentChar || $currentSegmentChar == '') {
if($current_length >= $biggest_length) {
$biggestSegment = $currentSegment;
$biggest_length = $current_length;
}
$currentSegmentChar = $char;
$currentSegment = $char;
$current_length = 1;
}
elseif($currentSegmentChar != '') {
$currentSegment .= $char;
$current_length++;
}
}
if($current_length >= $biggest_length) {
$biggestSegment = $currentSegment;
}
return array("string" => $biggestSegment,"length" => $biggest_length);
}
print_r(getLongetSegment("RKKRGGG"));
?>
Result: GGG
You can use preg_match_all over here as
preg_match_all('/(.)\1+/i','RKKRRRRK',$res);
usort($res[0],function($a,$b){
return strlen($b) - strlen($a);
});
echo $res[0][0];
Not sure if I understood this quite right. Something like this:
function maxCharSequece($string1)
{
$maxSeq = $seq = 0;
$maxChar = $lastChar = null;
for( $i = 0; $i < strlen($string1); $i++ )
{
$c = $string1[$i];
if (!$lastChar) $lastChar = $c;
if ( $lastChar == $c ){
if ( ++$seq > $maxSeq ) $maxChar = $lastChar;
}
else {
$maxSeq = $seq;
$seq = 0;
}
}
return $maxChar;
}
You can use preg_replace_callback to receive all continuous segments and select the longest
$sq = '';
preg_replace_callback('/(.)\1+/',
function ($i) use (&$sq) {
if(strlen($i[0]) > strlen($sq)) $sq = $i[0];
}, $str);
echo $sq . " " . strlen($sq);

PHP URL Shortener error

I have this PHP code which is supposed to increase a URL shortener mask on each new entry.
My problem is that it dosen't append a new char when it hits the last one (z).
(I know incrementing is a safety issue since you can guess earlier entries, but this is not a problem in this instance)
If i add 00, it can figure out 01 and so on... but is there a simple fix to why it won't do it on its own?
(The param is the last entry)
<?php
class shortener
{
public function ShortURL($str = null)
{
if (!is_null($str))
{
for($i = (strlen($str) - 1);$i >= 0;$i--)
{
if($str[$i] != 'Z')
{
$str[$i] = $this->_increase($str[$i]);
#var_dump($str[$i]);
break;
}
else
{
$str[$i] = '0';
if($i == 0)
{
$str = '0'.$str;
}
}
}
return $str;
}
else {
return '0';
}
}
private function _increase($letter)
{
//Lowercase: 97 - 122
//Uppercase: 65 - 90
// 0 - 9 : 48 - 57
$ord = ord($letter);
if($ord == 122)
{
$ord = 65;
}
elseif ($ord == 57)
{
$ord = 97;
}
else
{
$ord++;
}
return chr($ord);
}
}
?>
Effectively, all you are doing is encoding a number into Base62. So if we take the string, decode it into base 10, increment it, and reencode it into Base62, it will be much easier to know what we are doing, and the length of the string will take care of itself.
class shortener
{
public function ShortURL($str = null)
{
if ($str==null) return 0;
$int_val = $this->toBase10($str);
$int_val++;
return $this->toBase62($int_val);
}
public function toBase62($num, $b=62) {
$base='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$r = $num % $b ;
$res = $base[$r];
$q = floor($num/$b);
while ($q) {
$r = $q % $b;
$q =floor($q/$b);
$res = $base[$r].$res;
}
return $res;
}
function toBase10( $num, $b=62) {
$base='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$limit = strlen($num);
$res=strpos($base,$num[0]);
for($i=1;$i<$limit;$i++) {
$res = $b * $res + strpos($base,$num[$i]);
}
return $res;
}
}

Categories