Check variable equals a certain number - php

I need to check to make sure a variable equals either 5, 10, 50 or 100. If it doesn't then I want to set it to 5. Can someone tell me what's wrong with this IF statement?
if (isset($_REQUEST['number']) && $_REQUEST['number'] !== "5" || $_REQUEST['number'] !== "10" || $_REQUEST['number'] !== "50" || $_REQUEST['number'] !== "100") {
$number = 5;
} else {
$number = $_REQUEST['number'];
}

You need to break up your logic to overcome operator precedence. When in doubt, use parenthesis.
I also inverted the logic. It reads more naturally.
if (isset($_REQUEST['number']) && ($_REQUEST['number'] == "5" || $_REQUEST['number'] == "10" || $_REQUEST['number'] == "50" || $_REQUEST['number'] == "100")) {
  $number = $_REQUEST['number'];
} else {
  $number = 5;
}
While the above works, you could also streamline it with something like in_array().
isset($_REQUEST['number']) && in_array($_REQUEST['number'], array(5, 10, 50, 100))

Try:
if (isset($_REQUEST['number']) && ($_REQUEST['number'] == "5" || $_REQUEST['number'] == "10" || $_REQUEST['number'] == "50" || $_REQUEST['number'] == "100")) {
$number = $_REQUEST['number'];
} else {
$number = 5;
}

You've got some very confusing code. Does nothing you said you wanted.
this should be it:
if (isset($_REQUEST['number']) && in_array($_REQUEST['number'], array(5, 10, 50, 100))) {
$number = (int) $_REQUEST['number'];
} else {
$number = 5;
}
Combined from other answers so thank everyone :)

You need to swap things around a bit:
if (!isset($_REQUEST['number']) || ($_REQUEST['number'] !== "5" && $_REQUEST['number'] !== "10" && $_REQUEST['number'] !== "50" && $_REQUEST['number'] !== "100")) {
$number = 5;
} else {
$number = $_REQUEST['number'];
}
Narration of the above: if number isn't set, make it 5. If it is set, but isn't 5, 10, 50, or 100, set it to 5. Otherwise, leave it as-is.

It may be easier in the long run to break the logic up into a different format to try to be a bit clearer, rather then having a single 'if' statement.
$acceptable = array(5, 10, 50, 100);
$number = null;
if (isset($_REQUEST['number']) {
$number = intval($_REQUEST['number']);
}
if (!in_array($number, $acceptable)) {
$number = 5;
}
But with keeping it as a single if statement:
if (
isset($_REQUEST['number']) && (
$_REQUEST['number'] === "5" ||
$_REQUEST['number'] === "10" ||
$_REQUEST['number'] === "50" ||
$_REQUEST['number'] === "100"
)
) {
$number = $_REQUEST['number'];
} else {
$number = 5;
}

Although iMoses, and others already laid down the basics of simplifying your routine, I would suggest making the in_array() check more strict. If you don't and $_REQUEST['number'] would, for instance equal '10F', it would also pass.
// I like to define default values up front.
$number = 5;
// since $_REQUEST['number'] should always be a string
// make in_array() check strictly against these string values
$allowedNumbers = array( '5', '10', '50', '100' );
// make in_array check strictly
if( isset( $_REQUEST['number'] ) && in_array( $_REQUEST['number'], $allowedNumbers, true ) )
{
// get proper integer value
$number = intval( $_REQUEST['number'] );
}
var_dump( $number );

Related

PHP Variable declaration not working in Laravel 5.4

I have the following code in a Laravel 5.4 Blade view:
#php($strVal = $character->Strength)
#php($strMod = 0)
<?php
if ($strVal == 10 || 11) {
$strMod = 0;
} elseif ($strVal == 12 || 13) {
$strMod = 1;
} elseif ($strVal == 14) {
$strMod = 2;
} else {
$strMod = 2;
}
?>
It takes data from a MySQL table.
$strVal is an int from the table. The code creates a var called $strMod and goes through a number of if/elseif statements to see what it will be equal to.
It's shown on a webpage as follows:
<div class="huge charMod">+{{$strMod}}</div>
My issue is that it displays as "+0" no matter what strVar equals. strVar is working fine, I can pull it from the DB and display it via {{ $strVal }} but strMod refuses to take a value other than 0.
$strVal == 10 || 11 will always return true
Because that's not how comparisons work in PHP. The == operator has a higher precedence than || operator, so it will be performed first.
It means that $strVal == 10 || 11 gets turned into false || 11 .. which is true.
Instead of that code, I would recommend:
$map = [
10 => 0,
11 => 0,
12 => 1,
13 => 1,
// you dont actually need 14, because default value is aready 2
];
$result = 2;
if (array_key_exists($strVal, $map)) {
$result = $map[$strVal];
}
$strVal = $result;
Or, if you are using PHP 7.0+ it all can actually be written as:
$map = [10 => 0, 11 => 0, 12 => 1, 13 => 1];
$strVal = $map[$strVal] ?? 2;
You need to change your if checks to
if ($strVal == 10 || $strVal == 11) {
$strMod = 0;
} elseif ($strVal == 12 || $strVal == 13) {
$strMod = 1;
} elseif ($strVal == 14) {
$strMod = 2;
} else {
$strMod = 2;
}
if ($strVal == 10 || 11) will always return true. If you want to check two values you need to specify that by using the variable == value again as in the example above.

Using 'and' and 'or' in an if/else PHP statement

I am attempting to use both AND and OR statements in my IF/ELSE statement, but I cannot get the desired effect.
What I would like to achieve is that if either 'a' or 'b' has a value of '1' but both 'c' and 'd' must be 1 then I get 'Yes'.
All my attempts have given me either 'Yes' or have not worked (blank screen).
<?php
$a = "0";
$b = "1";
$c = "1";
$d = "1";
if (($a == "1") || ($b == "1") && ($c == "1") && ($d == "1")) {
echo "Yes";
}
else {
echo "No";
}
?>
Thank you.
You need and extra parenthesis, to make sure the evaluation order will be done correctly, like in math:
if ( ( ($a == "1") || ($b == "1") ) && ($c == "1") && ($d == "1")) {
^ ^
That way, let's say for example:
$a = 1;
$b = 2;
$c = 1;
$d = 2;
The first parenthesis will be evaluated as true || false. The final result will be true.
So now you have true && ($c == "1") && ($d == "1")
$c = 1, so again, the next evaluation will be true && true && ($d == 1)
$d = 2, so the next round will be true && true && false, final result, in this example, will be false.
You need to add parenthesis.
Why?
Because inner parenthesis are evaluated first before outer parenthesis. Take this example:
((1 == 1 && (2 == 2)) || 3 == 3)
What will be evaluated first? The 2 == 2 then the 1 == 1 and then the 3 == 3. In your if condition, because you are mixing AND's and OR's, you will not get the desired affect.
( (($a == "1") || ($b == "1")) && ($c == "1") && ($d == "1") )
Should work for you. In fact you can do this so that it looks even better:
(($a == 1 || $b == 1) && $c == 1 && $d == 1)
Because it is not necessary to put 1 in quotes ie: "1". PHP's truthiness will evaluate 1 == "1" to be true. However if you wanted to check for an actual string that contains 1, then you would use the === operator.
$a = 1;
$b = "1"
$a == "1"; // true
$b == 1; // true
$a === "1"; // false
$b === "1"; // true
However for more information go here: http://php.net/manual/en/language.operators.precedence.php
The equality operators will be evaluated first, then &&, then ||. Parentheses will be evaluated before anything else, so adding them can change the order.
Check the answer In Java, what are the boolean "order of operations"?
It will always echo a Yes because PHP interpreter places The AND operation before the OR operation.
So your if statement interpretes like this:
If
a = 1 or b = 1 and c = 1 and d = 1
then
echo 'Yes'
else
echo 'No'
That's why you always get a yes..

PHP: Multiple Unique Random Integers In A Specific Range

I want to create 8 random integers, that are unique and in the range between 0 and 99.
Is there a neater solution, than the one that I thought of?
<?php
do {
$rnd1 = rand(0,99);
$rnd2 = rand(0,99);
$rnd3 = rand(0,99);
$rnd4 = rand(0,99);
$rnd5 = rand(0,99);
$rnd6 = rand(0,99);
} while (($rnd1 == $rnd2) ||
($rnd1 == $rnd3) ||
($rnd1 == $rnd4) ||
($rnd1 == $rnd5) ||
($rnd1 == $rnd6) ||
($rnd2 == $rnd3) ||
($rnd2 == $rnd4) ||
($rnd2 == $rnd5) ||
($rnd2 == $rnd6) ||
($rnd3 == $rnd4) ||
($rnd3 == $rnd5) ||
($rnd3 == $rnd6) ||
($rnd4 == $rnd5) ||
($rnd4 == $rnd6) ||
($rnd5 == $rnd6) );
?>
Try the code below.
It will create an array containing 8 random values between 0 and 99 while checking if they have been added already to ensure they are unique across.
$numbers = array();
while ( count($numbers) <= 8 ) {
$x = mt_rand(0,99);
if ( !in_array($x,$numbers) ) {
$numbers[] = $x;
}
}
print_r($numbers);
Also see these two Q&A's about using mt_rand vs. rand
Difference between mt_rand() and rand()
What's the disadvantage of mt_rand?
This is an optimized version that relies on the array indexes. The complexity of this solution is linear rather than n2 as in #AlexAndrei's answer. It relies on using array indexes as the guarantee there are no duplicates so there is no need to add the overhead of in_array.
$random_numbers = [];
do {
$rand = rand(0, 99);
$random_numbers[$rand] = $rand;
} while( count($random_numbers) < 9 );
$random_numbers = array_values($random_numbers); // This strips the keys
print_r($random_numbers);
If you are using a foreach you can even drop the array_values call which would also increase the speed of your code, but the numbers in the array will be in the form: [ a => a, b => b, ... ]
$rnds = [];
do {
$newRnd = rand(0, 99);
$rnds[] = $newRnd;
} while(in_array($newRnd, $rnds) && count($rnds) < 9);
print_r($rnds);

php search within string for word?

I'm using PHP's preg_match to help determine the value of a string.
But the code only ever prints 1 or 2.
Why aren't the last two cases of my if statement ever matched?
$atype = strtolower($userData['user_type']); // let say data is :: company introducer
if ($atype == "individual introducer" || $atype == "individualintroducer" ||
(preg_match('/i/',$atype) AND preg_match('/int/',$atype)) ) {
$atype = 1 ;
} elseif ($atype == "individual investor" || $atype == "individualinvestor" ||
(preg_match('/i/',$atype) AND preg_match('/inv/',$atype)) ) {
$atype = 2;
} elseif ($atype == "company introducer" || $atype == "companyintroducer" ||
(preg_match('/c/',$atype) AND preg_match('/int/',$atype)) ){
$atype = 3;
} elseif ($atype == "company investor" || $atype == "companyinvestor" ||
(preg_match('/c/',$atype) AND preg_match('/inv/',$atype)) ){
$atype = 4;
}
echo $atype;
You need to explain your question in a better way.
But i guess as you say the data assumed is company introducer.
So it already matches condition for the first if block.
For ex:
In company introducer
The preg_match will return true.
if($atype == "individual introducer" || $atype == "individualintroducer" || (preg_match('/i/',$atype) AND preg_match('/int/',$atype)) ){
$atype =1 ;
}

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';
}

Categories