why the if else statement does not run the else statement? - php

I have a problem with my if and else statement in PHP where it never runs the else statement.
The input form is in HTML:
<input type="radio" name="marital_stat" id="single" value="single" />Single
<input type="radio" name="marital_stat" id="married" value="married" />Married
<input name="age" type="text" size="5" maxlength="3" placeholder="30" required/>
<input name="work" type="radio" id="employee" value="employee" />Employee
<input name="work" type="radio" id="own" value="own" />
Own Business
<input name="work" type="radio" id="jobless" value="jobless" />Jobless
<input name="place" type="radio" id="urban" value="urban" />Urban
<input name="place" type="radio" id="rural" value="rural" />Rural</td>
Here is the PHP Code:
if ($marital_stat == 'married')
{
if ($age >= 18 || $age < 59)
{
if ($work == 'jobless')
{
if ($place == 'rural') { $loan_credibility == 5; }
}
}
}
else if ($marital_stat == 'single')
{
if ($age >= 18 || $age < 59)
{
if ($work == 'employee')
{
if ($place == 'rural') { $loan_credibility == 1; }
}
}
}
Here is a condition that will display some output:
$A = 'positive';
$B = 'negative';
if ($loan_credibility == 5 ){
echo $B ;}
else{
echo $A;
}

As I see you make $loan_credibility == 5; or 1; the == only used in equality statement it checks the two sides if they equal and you have to use = to set value, not == so it will be $loan_credibility = 5; or 1;

You have no else clause (which logically is necessary when using else if)...
if (condition) {
code to be executed if condition is true;
} elseif (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
Do any of the following (#1 or #2 make the most sense)...
Make your else if into a separate if block
Change else if to else
Or add an else clause
Also, as #Mohamed Belal pointed out, when setting variables use = not ==.
So two things to fix your problem: 1) if-else if-else logic and 2) = vs ==...
if ($marital_stat == 'married')
{
if ($age >= 18 || $age < 59)
{
if ($work == 'jobless')
{
if ($place == 'rural') { $loan_credibility = 5; }
}
}
}
if ($marital_stat == 'single')
{
if ($age >= 18 || $age < 59)
{
if ($work == 'employee')
{
if ($place == 'rural') { $loan_credibility = 1; }
}
}
}

Related

PHP basic: why my variable showing wrong value?

I am new to PHP. I am trying to create a simple form where user will submit there name and mark they got in the exam.
<form action="" method="post">
<input type="text" name="name" id="" placeholder="Your name">
<input type="number" name="mark" id="" placeholder="Your Mark">
<input type="submit" name="submit" value="Submit">
</form>
<?php
if(isset($_POST["submit"])){
$name = $_POST['name'] ;
$mark = $_POST['mark'];
if( $mark > 80 ){
$result = "A+";
}elseif($mark > 70 && $mark < 80){
$result = "A";
}
elseif($mark > 60 && $mark < 70){
$result = "A-";
}
elseif($mark > 40 && $mark < 60){
$result = "B";
}else{
$result = "Fail";
}
echo $result;
}
?>
But if I echo the result variable it is always showing 'Fail'. What is I am doing wrong? thanks
As mentioned in the comments, when comparing ranges, you need to consider the corner cases:
$mark >= 70 && $mark < 80
Also there are few ways to simplify your code: If you check for marsk >= 80 in the first IF, there is no need to check for that in the next elseif:
if( $mark >= 80 )
{
$result = "A+";
}
elseif($mark >= 70)
{
$result = "A";
}
elseif($mark >= 60)
{
$result = "A-";
}
elseif($mark >= 40)
{
$result = "B";
}
else
{
$result = "Fail";
}
echo $result;

php - undefined variable - declared inside if statement

I have the following code that suppose to change the background color after I enter the RGB color codes and click submit.
I don't know for what reason I get the "Undefined variable" and have a black background color before I click the submit button
< ?php
error_reporting(E_ALL);
ini_set('display_errors',true);
$form = "< form method='post' action=$_SERVER[PHP_SELF] >\n
R: < input type='text' name='r' >
G: < input type='text' name='g' >
B: < input type='text' name='b' >
< input type='submit' name='buton' value='go' >\n";
< /form >
$hexa = array();
$culoareHexa = array();
function &decimal2hexa($valoare) {
$valoriHexa = array('0'=>'0', '1'=>'1', '2'=>'2', '3'=>'3', '4'=>'4', '5'=>'5', '6'=>'6', '7'=>'7', '8'=>'8', '9'=>'9', '10'=>'A', '11'=>'B', '12'=>'C', '13'=>'D', '14'=>'E', '15'=>'F' );
if ($valoare <= 15) {
$numarHexa[] = $valoare;
$numarHexa[] = 0;
} else {
while ($valoare >= 15) {
$catul = $valoare / 16;
settype($catul, 'int');
$restul = $valoare % 16;
$valoare = $catul;
$numarHexa[] = $restul;
}
$numarHexa[] = $catul;
}
krsort($numarHexa);
foreach ($numarHexa as $key => $value) {
if ($value > 9) {
$numarHexa[$key] = $valoriHexa[$value];
}
}
$numarHexa = array_values($numarHexa); //reindexez si pastrez valorile pe pozitia initiala
return $numarHexa;
}
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
echo $form;
} else {
if (!isset($_POST['r']) || !is_numeric($_POST['r']) || ($_POST['r'] > 255) || ($_POST['r'] < 0) ||
!isset($_POST['g']) || !is_numeric($_POST['g']) || ($_POST['g'] > 255) || ($_POST['g'] < 0) ||
!isset($_POST['b']) || !is_numeric($_POST['b']) || ($_POST['b'] > 255) || ($_POST['b'] < 0)) {
echo "date invalide!";
echo $form;
} else {
$culoareHexaR =& decimal2hexa($_POST['r']);
$culoareHexaG =& decimal2hexa($_POST['g']);
$culoareHexaB =& decimal2hexa($_POST['b']);
var_dump($_POST);
var_dump($culoareHexaR);
var_dump($culoareHexaG);
var_dump($culoareHexaB);
$culoareHexa = array_merge($culoareHexaR, $culoareHexaG, $culoareHexaB);
var_dump($culoareHexa);
$culoareHexaString = "";
for ($i = 0; $i < count($culoareHexa); $i++) {
$culoareHexaString .= $culoareHexa[$i];
}
echo $culoareHexaString;
}
}
? >
< html >
< body bgcolor="< ?php echo $culoareHexaString ? >">
< /body >
< /html >
If I declare the $culoareHexaString outside the if statement, it works just fine but I do not understand why.
in the following example it is not necessary to declade the $c variable outside the if statement.
$a = 5;
$b = 6;
if ($a > $b) {
echo "this will not be print";
} else {
$c = $a+$b;
}
$c variable will have a value of: < ?php echo $c ? >
what I am missing?
thanks!
Here:
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
...
} else {
// code not executed on GET/initial page view
}
You initialize $culoareHexaString in a block that is never executed, because the first view/non-submit is a GET request, and thuse the else condition is ignored.
Try initializing a default value outside that block, like:
$coloareHexaString = '#000000'; // default value?
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
...
} else {
// code not executed on GET/initial page view
}
As for your example, echoing $c would also be undefined if $a < $b, as it was never initialized.
<?php
$a = 7;
$b = 6;
if ($a > $b) {
echo "this will not be print";
} else {
$c = $a+$b;
}
echo $c; // this will be undefined.
?>
Because $culoareHexaString is not setted.
When you use if-else statement, actually there will be code blocks and at the run time according to the statement related block content is handling.
for detecting value setting, use isset() method.
Also you can set default color at the beginning like;
< ?php
error_reporting(E_ALL);
ini_set('display_errors',true);
$culoareHexaString = "#000000";
$form = "< form method='post' action=$_SERVER[PHP_SELF] >\n
R: < input type='text' name='r' >
G: < input type='text' name='g' >
B: < input type='text' name='b' >
< input type='submit' name='buton' value='go' >\n";
< /form >
$hexa = array();
$culoareHexa = array();
.....

Check Prime Number In PHP

My html document has the following form:
<form action="PrimeNumber.php" method="post">
Enter a number to determine if it is a prime number: <input type="text" name="numb" size="10">
<input type="submit" value="Check for Primeness">
</form>
Edit: Using a different code now but can't get it to echo a statement no matter what I do. Anyone know how I can make it echo is a prime number or is not.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['numb'])) {
$num = $_POST['numb'];
function isPrime($num) {
if($num == 1) {
return false;
}
if($num == 2) {
return true;
}
if($num % 2 == 0) {
return false;
}
for($i = 3; $i <= ceil(sqrt($num)); $i = $i + 2) {
if($num % $i == 0)
return false;
}
return true;
}
}
}
?>
simple and easy to understand code, and working as well. do little changes according to your requirement, like assign input text value to $a variable and you good to go.
$a = 51;
for($i=2; $i < $a; $i++){
if($a % $i == 0){
echo "Numberis not prime.";
break;
}
else{
echo "Number is not prime.";
break;
}
}
A simple function to check is prime number:
function is_prime($p) {
return ($p > 1) && (($p%2 >= 1) && ($p%3 >= 1) && ($p%5 >= 1)) || in_array($p, [2,3,5]);
}
function checkPrime($num){
$isPrime = true;
for($i = 2; $i <= sqrt($num); $i++)
{
if($num % $i == 0)
{
$isPrime = false;
}
}
if($isPrime == true)
{
return "$num is prime number";
}else{
return "$num is not prime number";
}
}
echo checkPrime(29);
The output is
29 is prime number
For More Details
You may use the gmp package and correct your code because I got an output as 11 not being a prime number or use the following function as an alternative.
function isPrime($num) {
if($num == 1) {
return false;
}
if($num == 2) {
return true;
}
if($num % 2 == 0) {
return false;
}
for($i = 3; $i <= ceil(sqrt($num)); $i = $i + 2) {
if($num % $i == 0)
return false;
}
return true;
}
More information is available at the following page.
A simple function to help you find out if a number is a prime number
<?php
function fn_prime($number) {
$i = 2; $result = TRUE;
while($i < $number) {
if(!($number%$i)) {
$result = FALSE;
}
$i++;
}
return $result;
}
?>

How to check for numbers only (including negative)?

how can I check for numbers only from -10 negative to +10 positive?
This is what I have, but I think it's not safe:
if(isset($_POST['number']) && ctype_digit($_POST['number']) && $_POST['number']>=-10 && $_POST['number']<=10){
//do something
}
and the form:
Input a number between -10 and 10: <input type="text" name="number" size="5" />
if( isset($_POST['number'])) {
$num = intval($_POST['number']);
if( $num >= -10 && $num <= 10) {
// do something
}
}
There are other ways, but that one will work. Anything that can't be converted to a number will be treated as zero. If this is not desired behaviour, add:
&& "".$num == $_POST['number']
To that inner IF statement, to ensure that no non-numeric characters were removed from the input.
Check whether a variable is a number including zero and negative values
$x = '-22';
if (isNumber($x, ['zero','negative']))
echo 'Yes';
else
echo 'No';
isNumber($x, $includes=[])
{
if (is_int($x)) {
if ($x === 0) {
if (in_array('zero', $includes))
return true;
} elseif ($x < 0) {
if (in_array('negative', $includes))
return true;
} else
return true;
} elseif (is_string($x)) {
if ($x == '0') {
if (in_array('zero', $includes))
return true;
} elseif ($x[0] == '-') {
if (in_array('negative', $includes))
return ctype_digit(substr($x, 1));
} else
return ctype_digit($x);
}
}

Notification Preferences Predicament

I am building a page which allows our members to select their notification preferences based on a number of options. For example sake, I am giving the option for the member to select notifications when a new message arrives and when an update has occured. They can receive the notification via email, sms, both, or neither.
If I simply build it out as a number of:
HTML code
<tr>
<td>Alert me when a new message comes in:</td>
</tr>
<tr>
<td>
<label><input name="ENREME" type="radio" style="margin-left:30px;" value="EMAIL" <?php if ($smscode == "7" || $smscode == "4") { ?>checked="checked"<?php } ?> tabindex="15" />Email</label>
<label><input name="ENREME" type="radio" style="margin-left:30px;" value="SMS" <?php if ($smscode == "7" || $smscode == "5") { ?>checked="checked"<?php } ?> />SMS</label>
<label><input name="ENREME" type="radio" style="margin-left:30px;" value="BOTH" <?php if ($smscode == "7" || $smscode == "6") { ?>checked="checked"<?php } ?> tabindex="15" />Both</label>
<label><input name="ENREME" type="radio" style="margin-left:30px;" value="NONE" <?php if ($smscode == "0") { ?>checked="checked"<?php } ?> />Don't notify me</label>
</td>
</tr>
<tr>
<td>Alert me when a new update to my site occurs:</td>
</tr>
<tr>
<td>
<label><input name="RECRUITEME" type="radio" style="margin-left:30px;" value="EMAIL" <?php if ($smscode == "7" || $smscode == "1") { ?>checked="checked"<?php } ?> tabindex="15" />Email</label>
<label><input name="RECRUITEME" type="radio" style="margin-left:30px;" value="SMS" <?php if ($smscode == "7" || $smscode == "2") { ?>checked="checked"<?php } ?> /> SMS</label>
<label><input name="RECRUITEME" type="radio" style="margin-left:30px;" value="BOTH" <?php if ($smscode == "7" || $smscode == "3") { ?>checked="checked"<?php } ?> tabindex="15" />Both</label>
<label><input name="RECRUITEME" type="radio" style="margin-left:30px;" value="NONE" <?php if ($smscode == "0") { ?>checked="checked"<?php } ?> />Don't notify me</label>
</td>
</tr>
Variable Encoding and Storage
<?php
if ($_POST['ENREME'] == "BOTH" && $_POST['RECRUITEME'] == "BOTH") {
$notif = 15;
} elseif ($_POST['ENREME'] == "BOTH" && $_POST['RECRUITEME'] == "SMS") {
$notif = 14;
} elseif ($_POST['ENREME'] == "BOTH" && $_POST['RECRUITEME'] == "EMAIL") {
$notif = 13;
} elseif ($_POST['ENREME'] == "BOTH" && $_POST['RECRUITEME'] == "NONE") {
$notif = 12;
} elseif ($_POST['ENREME'] == "EMAIL" && $_POST['RECRUITEME'] == "BOTH") {
$notif = 11;
} elseif ($_POST['ENREME'] == "EMAIL" && $_POST['RECRUITEME'] == "SMS") {
$notif = 10;
} elseif ($_POST['ENREME'] == "EMAIL" && $_POST['RECRUITEME'] == "EMAIL") {
$notif = 9;
} elseif ($_POST['ENREME'] == "EMAIL" && $_POST['RECRUITEME'] == "NONE") {
$notif = 8;
} elseif ($_POST['ENREME'] == "SMS" && $_POST['RECRUITEME'] == "BOTH") {
$notif = 7;
} elseif ($_POST['ENREME'] == "SMS" && $_POST['RECRUITEME'] == "SMS") {
$notif = 6;
} elseif ($_POST['ENREME'] == "SMS" && $_POST['RECRUITEME'] == "EMAIL") {
$notif = 5;
} elseif ($_POST['ENREME'] == "SMS" && $_POST['RECRUITEME'] == "NONE") {
$notif = 4;
} elseif ($_POST['ENREME'] == "NONE" && $_POST['RECRUITEME'] == "BOTH") {
$notif = 3;
} elseif ($_POST['ENREME'] == "NONE" && $_POST['RECRUITEME'] == "SMS") {
$notif = 2;
} elseif ($_POST['ENREME'] == "NONE" && $_POST['RECRUITEME'] == "EMAIL") {
$notif = 1;
} elseif ($_POST['ENREME'] == "NONE" && $_POST['RECRUITEME'] == "NONE") {
$notif = 0;
}
?>
I am left to code for 16 possible variables (and thus creating over 100 lines of code). Can anybody think of a better way to consolidate this code? Based on the selections made, I want the result to equal a single digit (i.e. 28 equals, send email and SMS notifications for both new messages and updates).
Creating a new table or database and making reference calls is not a solution so please do not suggest that.
Thank you!
This is an example on how NOT knowing C puts you against a wall when developing simple things. As far as I can see, the simplest option is the best, just use binary!:
define('SEND_EMAIL',1);
define('SEND_SMS',2);
/* The values are packed together, low bits represent 'update' options,
* high bits represent 'message' options
* You can save up to 4 variants (ON/OFF) with 0xf
*/
$options = ((intval($_POST['message']) & 0xf) << 4) | (intval($_POST['update']));
...
// Retrieve options from, say, stored option
$message = ($options >> 4) & 0xf;
$update = $options & 0xf;
/* For readability, this can be a function */
if ($message == (SEND_SMS|SEND_EMAIL)) {
$message = 'Both';
}
else if ($message == SEND_SMS) {
$message = 'SMS';
}
else if ($message == SEND_EMAIL) {
$message = 'Email';
}
It sounds like what you're really looking for is a bitwise solution. Using bits, you're able to store a lot of boolean switches into a single integer. This answer uses some roundabouts to keep things clear - you could use the int values directly instead of the pow(2,X) shown below... consider it "teaching a man to fish".
If you'd like a more succint, though complex to understand solution, take a look at Ast Derek's answer. They both do the same thing and operate on the same principle.
In order to store these, let's do two simple switches:
switch($_GET['x']) {
case 'Email': $x = pow(2,0); break; // 1
case 'Sms': $x = pow(2,1); break; // 2
case 'Both': $x = pow(2,0) + pow(2,1); break;// 3
default: $x = 0;
}
switch($_GET['y']) {
case 'Email': $y = pow(2,2); echo "Y Email"; break; // 4
case 'Sms': $y = pow(2,3); echo "Y SMS"; break; // 8
case 'Both': $y = pow(2,2) + pow(2,3); echo "Y Both"; break; // 12
default: $y = 0;
}
As you can see, the None options are absent. None is simply the absence of a either Email or SMS. Also, the Both option is defined not as a separate option, but as a combination of both.
Now that we have these value, we can combine these two numbers into a single number, since their relevant bits are both in different ranges.
$z = $x | $y;
What happens when looking at the bits is the following - assume that we've got X = Email, and Y = Both.
x = 0001 -> (0 + 0 + 0 + 1) -> 1
y = 1100 -> (8 + 4 + 0 + 0) -> 12
-----
OR: 1101 -> (8 + 4 + 0 + 1) -> 13
What this will give you is the following possible results:
0: x = none, y = none
1: x = email, y = none
2: x = sms, y = none
3: x = both, y = none
4: x = none, y = email
5: x = email, y = email
6: x = sms, y = email
7: x = both, y = email
8: x = none, y = sms
9: x = email, y = sms
10: x = sms, y = sms
11: x = both, y = sms
12: x = none, y = both
13: x = email, y = both
14: x = sms, y = both
15: x = both, y = both
To detect which have chosen, simply reverse the operation.
So you can test things, I've put the whole setup in a Github Gist for you to enjoy and tinker with: http://gist.github.com/505272
Feel free to ask if you need clarification; I'm not sure I explained it very clearly :/

Categories