If ... do this if statement? - php

I am stuck on some php coding, that seemed initially easy to accomplish. Here is what i would like to do :
<?php
$amountOfDigits = 1;
$numbers = range(1,3);
shuffle($numbers);
for($i = 0;$i < $amountOfDigits;$i++)
$digits .= $numbers[$i];
while ( have_posts() ) : the_post();
static $count = 0;
if ($digits == '1') {
//Do this if statement
if ($count == "2") }
elseif ($digits == '2') {
//Do this if statement
if ($count == "2" || $count == "3") }
elseif ($digits == '3') {
//Do this if statement
if ($count == "2" || $count == "3" || $count == "4") }
{ //here the rest of the code
?>
So depending on the $digits variable, the if statement is formatted to be used on the line above //the rest of the code
How to put this in PHP properly?
Thanks.
Robbert

If I understand your question properly, you want something like this:
if ($digits == '1')
$mycond = ($count == "2");
elseif ($digits == '2')
$mycond = ($count == "2" || $count == "3")
elseif ($digits == '3')
$mycond = ($count == "2" || $count == "3" || $count == "4")
then you can further use
if($mycond){
// blahblahblah
}

Well if you want the same execution block on each case, there is a very simple solution for that.
You should simply use a function that check status of "count" depending on "digits".
<?php
function checkCountAgainstDigits($count, $digits){
switch($digits){
case 1:
return $count === 1;
case 2:
return $count === 2 || $count === 3;
case 3:
return $count === 2 || $count === 3 || $count === 4;
default:
// The default case "ELSE"
return FALSE;
}
}
if(checkCountAgainstDigits($count, $digits)){
// do
}
?>
If you want a different one, your solution is correct.

Related

Optimisation exercise in PHP

I am trying to automatically fill in a form with '0' if there is no value supplied. There are 14 questions to be filled in. The code I've written is ugly but works. I am looking to improve it by setting an array with all the questions and loop the command untill all the boxes are filled in with values or 0.
if ($q1 == '') {
$q1 = '0';
}
if ($q2 == '') {
$q2 = '0';
}
if ($q3 == '') {
$q3 = '0';
}
if ($q4 == '') {
$q4 = '0';
}
//... and so on up to $q14
if ($q13 == '') {
$q13 = '0';
}
if ($q14 == '') {
$q14 = '0';
}
Ideally, you should be using an array for these variables. Then you could simply loop through the indexes of the array to test and change as required. If you cannot change that, you can use variable variables to simplify the code:
for ($i = 1; $i <= 14; $i++) {
if (${"q$i"} == '') ${"q$i"} = 0;
}
If you do put the values in an array, you can loop through it with a foreach. Note the use of &$v to allow us to change the value in the loop:
foreach ($q as &$v) {
if ($v == '') $v = 0;
}
Demo on 3v4l.org

Calculate Poker Hand

My charity does "Poker Runs" motorcycle runs where player go to each stop and pick a card. We are looking to make this an easier way to track the winners without having to manually sort through each card.
I believe I have all other functions done, I just am unsure how to check for the full house with the method I am using. And also how to score just for a high card hand.
<?php
$card_one_suit = $_POST['card_one_suit'];
$card_two_suit = $_POST['card_two_suit'];
$card_three_suit = $_POST['card_three_suit'];
$card_four_suit = $_POST['card_four_suit'];
$card_five_suit = $_POST['card_five_suit'];
$card_one = $_POST['card_one'];
$card_two = $_POST['card_two'];
$card_three = $_POST['card_three'];
$card_four = $_POST['card_four'];
$card_five = $_POST['card_five'];
$player = $_POST['name'];
$total_card_amount = $card_one + $card_two + $card_three + $card_four + $card_five;
$card_list = array();
array_push($card_list, $card_one, $card_two, $card_three, $card_four, $card_five);
$card_suits = array();
array_push($card_suits, $card_one_suit, $card_two_suit, $card_three_suit, $card_four_suit, $card_five_suit);
$rank = 0;
foreach($card_list as $card)
{
$count_values[$card]++;
}
foreach($card_suits as $cards)
{
$count_suit_values[$cards]++;
}
//echo "$count_suit_values[$card_one_suit]";
//print_r($count_suit_values);
// ROYAL FLUSH
if(($total_card_amount == "60") && ($count_suit_values[$card_one_suit] == 5))
{
$rank = 1;
echo "ROYAL FLUSH";
}
// STRAIGHT FLUSH
else if (($total_card_amount == "20" || $total_card_amount == "25" || $total_card_amount == "30" || $total_card_amount == "35" || $total_card_amount == "40") &&
($count_suit_values[$card_one_suit] == 5))
{
$rank = 2;
echo "STRAIGHT FLUSH";
}
// FOUR OF A KIND
else if ($count_values[$card_one] == 4 || $count_values[$card_two] == 4 || $count_values[$card_three] == 4)
{
$rank = 3;
echo "FOUR OF A KIND";
}
// FULL HOUSE
// HOW TO FIGURE THIS OUT?
// FLUSH
else if ($count_suit_values[$card_one_suit] == 5 || $count_suit_values[$card_two_suit] == 5 || $count_suit_values[$card_three_suit] == 5)
{
$rank = 5;
echo "FLUSH";
}
// STRAIGHT
else if ($total_card_amount == "20" || $total_card_amount == "25" || $total_card_amount == "30" || $total_card_amount == "35" || $total_card_amount == "40")
{
$rank = 6;
echo "STRAIGHT";
}
// THREE OF A KIND
else if ($count_values[$card_one] == 3 || $count_values[$card_two] == 3 || $count_values[$card_three] == 3 || $count_values[$card_four] == 3)
{
$rank = 7;
echo "THREE OF A KIND";
}
// TWO PAIR
else if ($count_values[$card_one] == 2 && $count_values[$card_two] == 2 || $count_values[$card_one] == 2 && $count_values[$card_three] == 2
|| $count_values[$card_one] == 2 && $count_values[$card_five] == 2 || $count_values[$card_two] == 2 && $count_values[$card_three] == 2)
{
$rank = 8;
echo "TWO PAIR";
}
// ONE PAIR
else if ($count_values[$card_one] == 2 || $count_values[$card_two] == 2 || $count_values[$card_three] == 2 || $count_values[$card_four] == 2)
{
$rank = 9;
echo "ONE PAIR";
}
// HIGH CARD
else
{
$rank = 10;
echo "NO MATCHES. DETERMINE HIGH CARD";
}
?>
For the hand to be a full house, the array count_values must contain two entries, one of those entries must have a value of 3.
else if (count($count_values) == 2 && (array_values($count_values)[0] == 3 || array_values($count_values)[1] == 3)) {
echo 'FULL HOUSE';
}

Unable to increase value in php

I have a function where, if the user enters the correct answer, the score should increment. The validation function is working fine, but the score is not incrementing. Initially, I defined it as 0 and then it should increment based on the answer, but it's not working.
$score =0;
function checkscore ($n, $ans)
{
global $score;
$arr = array('a', 'd');
if (($n == 1) && ($ans == (count(array_intersect($arr, $_POST['a'])) == count($arr))))
{
$score++;
}
if (($n == 2) && ($ans == ($_POST['b'] == 'a')))
{
$score++;
}
if (($n == 3) && ($ans == "div[id='serenade']"))
{
$score++;
}
if (($n == 4) && ($ans != (($_POST['d1'] == 'B') && ($_POST['d2'] == 'C') && ($_POST['d3'] == 'A'))))
{
$score++;
}
return $score;
}
This is the function. Someone please help me.
This function will return 1 if $n is 3 or 4, 0 otherwise. The first two conditions will always be false, while the third will be true when $n==3 and the fourth when $n==4.
So it does increment occasionally, but only up to 1...

Working around for loop [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I have noticed similar repetition and trying to work around using a single for loop for this if I can to minimize the code length:
I wouldn't need to use a switch case if I can form a loop instead?
$returnNo variable starts at 5, each case multiplied by 2 then minus 1.
where it shows "$a<=", it starts at 5 and each case multiplied by 2 then plus 3.
the if() statement starting at if($matchno == 7), each case multiplied by 2 then plus 1.
the final if() statement starting at if($matchno == 8), each case multiplied by 2.
I have done up to case 64, it will actually go up to 512. As I know the code is repeating I am hoping someone can help me produce a single loop for this?
Many thanks!
switch($max) {
case 80 :
$returnNO = 5;
for($a = 1; $a<=5; $a++) {
if($matchno == $a || $matchno == ($a+1)){
$matchinfo['matchno'] = $returnNO;
$matchinfo['place'] = ($matchno == $a ? 'clan1' : 'clan2');
return $matchinfo;
}
$returnNO++;
$a++;
}
if($matchno == 7){
$matchinfo['winner'] = true;
return $matchinfo;
}elseif($matchno == 8){
$matchinfo['third_winner'] = true;
return $matchinfo;
}
break;
case 160 :
$returnNO = 9;
for($a = 1; $a<=13; $a++) {
if($matchno == $a || $matchno == ($a+1)){
$matchinfo['matchno'] = $returnNO;
$matchinfo['place'] = ($matchno == $a ? 'clan1' : 'clan2');
return $matchinfo;
}
$returnNO++;
$a++;
}
if($matchno == 15){
$matchinfo['winner'] = true;
return $matchinfo;
}elseif($matchno == 16){
$matchinfo['third_winner'] = true;
return $matchinfo;
}
break;
case 320 :
$returnNO = 17;
for($a = 1; $a<=29; $a++) {
if($matchno == $a || $matchno == ($a+1)){
$matchinfo['matchno'] = $returnNO;
$matchinfo['place'] = ($matchno == $a ? 'clan1' : 'clan2');
return $matchinfo;
}
$returnNO++;
$a++;
}
if($matchno == 31){
$matchinfo['winner'] = true;
return $matchinfo;
} elseif($matchno == 32){
$matchinfo['third_winner'] = true;
return $matchinfo;
}
break;
case 640 :
$returnNO = 33;
for($a = 1; $a<=61; $a++) {
if($matchno == $a || $matchno == ($a+1)){
$matchinfo['matchno'] = $returnNO;
$matchinfo['place'] = ($matchno == $a ? 'clan1' : 'clan2');
return $matchinfo;
}
$returnNO++;
$a++;
}
if($matchno == 63){
$matchinfo['winner'] = true;
return $matchinfo;
}elseif($matchno == 64){
$matchinfo['third_winner'] = true;
return $matchinfo;
}
break;
}
}
I'll use the first two cases as an example:
switch ($max) {
case 80:
$returnNO = 5;
$loopCount = 5;
$winner = 7;
$thirdWinner = 8;
break;
case 160:
$returnNO = 9;
$loopCount = 13;
$winner = 15;
$thirdWinner = 16;
break;
...
}
for ($a = 1; $a <= $loopCount; $a++) {
if ($matchno == $a || $matchno == ($a + 1)) {
$matchinfo['matchno'] = $returnNO;
$matchinfo['place'] = ($matchno == $a ? 'clan1' : 'clan2');
return $matchinfo;
}
}
if ($matchno == $winner) {
$matchinfo['winner'] = true;
return $matchinfo;
} else if ($matchno == $thirdWinner) {
$matchinfo['third_winner'] = true;
return $matchinfo;
}
Simply explained, remove the code that repeats all the time and try to parameterize it (either by creating a function or by putting all repeated code somewhere else... in this example, I put the repeating code after the switch statement and paremeterized it.
If I understood well, here is an alternative solution which I think would work for all cases you specified, with no use of switch case.
$div10 = $max / 10;
$maxLoop = $div10 - 3;
$returnNO = $div10 / 2 + 1;
for($a = 1; $a<=$maxLoop; $a++) {
if($matchno == $a || $matchno == ($a+1)){
$matchinfo['matchno'] = $returnNO;
$matchinfo['place'] = ($matchno == $a ? 'clan1' : 'clan2');
return $matchinfo;
}
$returnNO++;
$a++;
}
if($matchno == ($div10-1)){
$matchinfo['winner'] = true;
return $matchinfo;
}elseif($matchno == $div10){
$matchinfo['third_winner'] = true;
return $matchinfo;
}

foreach() skipping first element in array

Trying to create a GPA Calculator. I have a form that submits to a php file and then stores all data from the form in a php array(). The calculator works great until I enter the same value. I think this wont make sense until I show some pictures:
Here is the problem in an image:
So in the first image I enter a A and then another A which outputs array(1) { [0]=> float(4.5) } when using var_dump()
And in the second image the var_dump() is array(2) { [0]=> float(4) 1=> float(3.5) }
It is skipping the first row in the first image... just in case A is supposed to equal 4.0 in REG and 4.5 in HONORS. It might be the array_combine()
Here is my php code:
//$_POST['grades'] for the grades <option> and $_POST['types'] for the type (REG, HONORS)
foreach(array_combine($_POST['grades'], $_POST['types']) as $code => $count)
{
if ($code == "A")
{
if ($count == "REGULAR")
{
$GradeArray[] = 4.0;
}
else if ($count == "HONORS")
{
$GradeArray[] = 4.5;
}
else if ($count == "COLLEGE")
{
$GradeArray[] = 5.0;
}
}
else if ($code == "B")
{
if ($count == "REGULAR")
{
$GradeArray[] = 3.0;
}
else if ($count == "HONORS")
{
$GradeArray[] = 3.5;
}
else if ($count == "COLLEGE")
{
$GradeArray[] = 4.0;
}
}
else if ($code == "C")
{
if ($count == "REGULAR")
{
$GradeArray[] = 2.0;
}
else if ($count == "HONORS")
{
$GradeArray[] = 2.5;
}
else if ($count == "COLLEGE")
{
$GradeArray[] = 3.0;
}
}
else if ($code == "D")
{
if ($count == "REGULAR")
{
$GradeArray[] = 1.0;
}
else if ($count == "HONORS")
{
$GradeArray[] = 1.5;
}
else if ($count == "COLLEGE")
{
$GradeArray[] = 2.0;
}
}
else if ($code == "F")
{
if ($count == "REGULAR")
{
$GradeArray[] = 0.0;
}
else if ($count == "HONORS")
{
$GradeArray[] = .5;
}
else if ($count == "COLLEGE")
{
$GradeArray[] = 1.0;
}
}
}
It might be the whole foreach() statement that needs reworking... I am up to writing the logic again if anyone says so...
I don't want to clog up the question with code so if you absolutely need the html just ask and I will add in an edit.
EDIT: I am also thinking I need to rewrite the logic... I have never used array_combine() before... I just need to make sure the corresponds with the related
Thanks for the help!
If you want to iterate over two arrays (or more) you could consider using the MultipleIterator; it doesn't clobber array keys like array_combine() does.
You could also simplify your logic by using an array to define the scores of each grade / type combination:
$gradesToScores = array(
'REGULAR' => array(
'A' => 4.0, 'B' => 3.0, 'C' => 2.0, 'D' => 1.0, 'F' => 0.0,
),
'HONORS' => array(
'A' => 4.5, 'B' => 3.5, 'C' => 2.5, 'D' => 1.5, 'F' => 0.5,
),
'COLLEGE' => array(
'A' => 5.0, 'B' => 4.0, 'C' => 3.0, 'D' => 2.0, 'F' => 1.0,
),
);
$gradeItemIterator = new MultipleIterator(MultipleIterator::MIT_KEYS_ASSOC);
$gradeItemIterator->attachIterator(new ArrayIterator($_POST['grades']), 'grade');
$gradeItemIterator->attachIterator(new ArrayIterator($_POST['types']), 'type');
$gradeScores = array();
foreach ($gradeItemIterator as $gradeItem) {
$gradeScores[] = $gradesToScores[$gradeItem['type']][$gradeItem['grade']];
}
look at this array and output look the VALUES "a" which becomes the key of the resultant array,
so if u want the full array to be combined with the key of first array then first array must kave unique values.
<?php
print_r(array_combine(Array('a','a','b'), Array(1,2,3)));
?>
Returns:
Array
(
[a] => 2
[b] => 3
)
solution (may not be the best )
foreach($_POST['grades'] as $KEY=>$code)
{
$count = $_POST['types'][$KEY];
if ($code == "A")
{
if ($count == "REGULAR")
{
$GradeArray[] = 4.0;
}
else if ($count == "HONORS")
{
$GradeArray[] = 4.5;
}
else if ($count == "COLLEGE")
{
$GradeArray[] = 5.0;
}
}
else if ($code == "B")
{
if ($count == "REGULAR")
{
$GradeArray[] = 3.0;
}
else if ($count == "HONORS")
{
$GradeArray[] = 3.5;
}
else if ($count == "COLLEGE")
{
$GradeArray[] = 4.0;
}
}
else if ($code == "C")
{
if ($count == "REGULAR")
{
$GradeArray[] = 2.0;
}
else if ($count == "HONORS")
{
$GradeArray[] = 2.5;
}
else if ($count == "COLLEGE")
{
$GradeArray[] = 3.0;
}
}
else if ($code == "D")
{
if ($count == "REGULAR")
{
$GradeArray[] = 1.0;
}
else if ($count == "HONORS")
{
$GradeArray[] = 1.5;
}
else if ($count == "COLLEGE")
{
$GradeArray[] = 2.0;
}
}
else if ($code == "F")
{
if ($count == "REGULAR")
{
$GradeArray[] = 0.0;
}
else if ($count == "HONORS")
{
$GradeArray[] = .5;
}
else if ($count == "COLLEGE")
{
$GradeArray[] = 1.0;
}
}
}
I agree with Arun on the reason for the behaviour. A possible solution would be:
$lookup = Array("A"=>4, "B"=>3, "C"=>2, "D"=>1, "F"=>0);
for ( $i=0; $i<count($_POST['grades']); $i++ ) {
$temp = $lookup[ $_POST['grades'][$i] ];
if ( $_POST['types'][$i] == "HONORS" ) {
$temp += .5;
}
elseif ( $_POST['types'][$i] == "COLLEGE" ) {
$temp += 1;
}
$GradeArray[] = $temp;
}
This assumes the count of $_POST['grades'] and $_POST['types'] to be equal - otherwise it will either cause an undefined offset notice or not address each value.
Regarding Arun's code: nesting the two loops will create N*M inner loop iterations - one for each combination of grade/type, clearly wrong in this case! We need to go through the arrays in parallel, as they are used to hold pair values.
#Jack: If I'm not mistaken, you need to swap HONORS and COLLEGE in your Array definition.
This solution works for me fine
$array = array('ab', 'bc', 'cd', 'de');
$array = array_combine(range(1, count($array)), array_values($array));
print_r($array);

Categories