PHP If/ Else statement not working. Just following 'IF' line - php

As simple as it seems, I dont know why this isn't working.
I have a form with a few drop down selects that if $message_type is equal to other, the message is constructed out of just the details from $details.
If $message_type is anything else, it should string together a message.
The variables are being passed and have checked that it is exactly 'Other' that is being passed through to the page using echo's so there is no spelling mistake.
At the moment, whatever the message type, it always just creates the message to be just $details and does not follow the 'else' line if it does not equal 'Other'.
if ($message_type = 'Other'){$message = $details;
}
else {$message = "Action to do: ".$message_type." On ".$user." Extra Details: ".$details;
}
Any help as this is now really confusing me.
Thanks

if ($message_type == 'Other')
{
$message = $details;
}
else
{
$message = "Action to do: ".$message_type." On ".$user." Extra Details: ".$details;
}
$message_type = 'Other' is alway true

What you did wrong were already explained by the other answer, but "why" does this happen? It's simple: = is the assignment operator and like any other operator in PHP (and many (all?) languages) the operator has a retun value, that is in this case the value of the assignment. PHP now cast this to a boolean and therefore it is true
if ($message_type = 'Other'){ /* .. */}
if ('Other'){ /* .. */}
if (true){ /* .. */}

if ($message_type = 'Other'){$message = $details;
}
else {$message = "Action to do: ".$message_type." On ".$user." Extra Details: ".$details;
}
you have if ($message_type = 'Other')
you should have if ($mesage_type == 'Other')
I suppose it is just writing mistake, so I wont be telling what is the diferance :)

You need two equal signs
if ($message_type == 'Other') {
-------------------^
$message = $details;
} else {
$message = "Action to do: ".$message_type." On ".$user." Extra Details: ".$details;
}
One equal sign is the assignment operator, so you are saying "$message_type is equal to 'Other'" instead of "if $message_type is equal to 'Other'"

Related

variable assign and check

Can Someone tell me what's wrong with this code
function someFunction($num=null) {
return $num;
}
if ($name = someFunction('mystr') && $name ) {
echo 'hello ';
}else {
echo 'hi';
}
Why it is going in else condition and giving me notice of undefined variable $name
Edited: - if i do like this
if($name = someFunction() && $name ){
echo 'hello';
} else {
echo 'hi';
}
this time its also going on else condition as it should but it also not showing the error as i understand it, php just check my first condition $name = someFunction() and its fail then just else
but if i do as i do previously $name = someFunction('str') now $name is set so why notice of undefined variable
sorry for bad grammer
just want to know what is happening here.
It's because logical operators like && have higher precedence than the assignment operator =. You can read more about this here: http://php.net/manual/en/language.operators.precedence.php
The line
if ($name = someFunction('mystr') && $name ) {
is being evaluated like this:
if ($name = (someFunction('mystr') && $name) ) {
where the expression in the inner brackets is evaluated first. Because $name has not been defined before this point, a notice is raised.
I think what you're trying to do is this:
if (($name = someFunction('mystr')) && $name ) {
where you assign the value mystr to $name and then also evaluate that it's "truthy". But as pointed out in the comments, this is a bit of a strange approach. The following code would be equivalent:
$name = 'mystr';
if ($name) {
...
This feels a bit like a problem that's been cut down a bit too much in order to explain it, because it's not really clear why you're doing this.
you code output : hi becuase there is $name is in second is always null.
function someFunction($num=null) {
return $num;
}
$name = someFunction('mystr');
if ($name && $name ) {
echo 'hello ';
}else {
echo 'hi';
}
output : mystr && mystr = 1 then output is hello
You haven't assigned anything to your variable $name and since it is an AND Condition, the first gets true but the second one doesn't so assign any value to your $name and add a condition for it to work.

Having an issue with PHP elseif code crashing script

I'm having an issue when I enable the code below that it is causing my code to crash. I can't figure out where its crashing but I know if I comment out this portion that it will allow the code to run, just not have the checks ran on the other portions of the form.
if (empty($_POST["SCreq"])) {{
$SCreqERR = "SC requires a Yes or No answer";
} else {
$SCreq = test_input($_POST["SCreq"]);}
// elseif($SCreq = "Yes"; $Email=False)
// $EmailERR = "Email is required for SC"
// elseif ($SCreq = "Yes"; $emaildist1 = "")
// $emaildist1ERR = "First Email Distrobution Group required with SC"
// else {
// $emaildist1 = test_input($_POST["emaildist1"])
}}
Any help would be greatly appreciated, I have everything name, and all is the correct case.
The double-quotes basically start a new block within your "if" block. So, your code could be written like this:
if (empty($_POST["SCreq"])) {
{
$SCreqERR = "SC requires a Yes or No answer";
}
else {
$SCreq = test_input($_POST["SCreq"]);
}
}}
Not only are the brackets unbalanced (there's more closing brackets than opening brackets), the "else" also starts inside the "if" block. Removing the {} inside the "if", you get
if (empty($_POST["SCreq"])) {
else {
$SCreq = test_input($_POST["SCreq"]);
}
}}
which isn't valid (the "else" has to come directly after the "if" block, not within it).
Use proper indenting to catch those mistakes quickly. After each "{", start a new line, and indent your code more. After each "}", start a new line, and indent less. After each block, you need to be at the same indent-level as you were before, otherwise you have extra "{"s or "}". You can either do that manually, or have a good editor that does it for you. This kind of code uses proper indenting, and would be valid:
if (empty($_POST["SCreq"])) {
$SCreqERR = "SC requires a Yes or No answer";
}
else {
$SCreq = test_input($_POST["SCreq"]);
}
Use an IDE to help check that things are nested correctly. Hard to tell with things commented out though but... {{. Also, error logs!
I assume you looked at the documentation? http://php.net/manual/en/control-structures.elseif.php
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
elseif($SCreq == "Yes" && $Email == False)
$EmailERR = "Email is required for SC";
elseif ($SCreq == "Yes" && $emaildist1 == "")
$emaildist1ERR = "First Email Distrobution Group required with SC";
else {
$emaildist1 = test_input($_POST["emaildist1"]);}
Condition test is ==
multiple AND condition put &&.
End your statements with ;

IF statement in a PHP file to detect when there aren't any entries

I have a job application form returning a person's details among other things.
Right now, these are returned on separate lines. And if there are no entries in any field, there is a blank line in the email that is sent.
I'd like to make an IF statement so that if there is no entry in any field, it will return "Not Applicable" in the mail.
example:
$nrel1 = $_POST['nrel1'];
$nrel11_name = $_POST['nrel1_name'];
$nrel1_age = $_POST['nrel1_age'];
$nrel1_gender = $_POST['nrel1_gender'];
$nrel1_education = $_POST['nrel1_education'];
$nrel2_employment = $_POST['nrel2_employment'];
Now if the applicant makes no entry in the $nrel1_age field, I want it to return "Not Applicable" in the mail.
function valueOrNotApplicable($array, $key)
{
if (isset($array[$key]) && !empty($array[$key]))
return $array[$key];
else
return 'Not Applicable';
}
$nrel1 = valueOrNotApplicable($_POST, 'nrel1');
$nrel11_name = valueOrNotApplicable($_POST, 'nrel1_name');
$nrel1_age = valueOrNotApplicable($_POST, 'nrel1_age');
$nrel1_gender = valueOrNotApplicable($_POST, 'nrel1_gender');
$nrel1_education = valueOrNotApplicable($_POST, 'nrel1_education');
$nrel2_employment = valueOrNotApplicable($_POST, 'nrel2_employment');
It's good to check both isset() and !empty(). If you don't check for isset() then you may get "PHP Notice: Undefined index" warnings.
$nrel1_age = empty($_POST['nrel1_age']) ? 'Not Applicable' : $_POST['nrel1_age'];
Try
$nrel1 = (!empty(trim($nrel1_age))) ? $_POST['nrel1'] : "Not applicable";
if(!isset($nrel1_age) && (trim($nrel1_age)!=''))
return "Not applicable";
That should do the trick. Cheers
EDIT
Forgot the trim part.
You can use conditional operator as below
$nrel1_age = isset($_POST['nrel1_age']) && trim($_POST['nrel1_age'])!=''?$_POST['nrel1_age']:'Not Available';

Problem with Boolean Values in PHP

I've some problems with handling Boolean values in PHP. It is a validation script before storing data into database. I wrote a global validator that will validate and return a Boolean value whether the validation was successful .
Here is my code.
//VALIDATE
$isValid = true;
foreach($team as $key=>$val) {
if(!is_array($val)){
$isValid = $isValid && validate($val, $key);
}
}
for($it=0;$it<count($team['members']);$it++){
foreach($team['members'][$it] as $key=>$val) {
$isValid = $isValid && validate($val, $key);
}
}
if(!$isValid) { // EDITED: if(!isValid)
echo "validation error";
exit(1);
}
//END OF VALIDATE
The validate function is working properly but sometimes I end up getting $isValid = true or the other way, when I try with some test cases.
Hmm.. What am I doing wrong here ?
Please check, if this form does the trick:
if( false === $isValid) {
echo "validation error";
exit(1);
}
Note, that ( ! $isValid ) or (false == $isValid ) in some cases return results, which are at first look wrong. See for example the hint in the strpos() documentation.
In fact, the results are fine, since operations line ! or == try to cast operands in a 'useful' way.
That said, it's always better to user the === operator, since it checks values and types of operands. Please see operator overview.
if(!isValid) { falls back to if (!"isValid"), if there is no constant isValid. You probably meant if (!$isValid) {.
if(!isValid) {
isValid has no dolar, (you need to give variables in PHP some cash) so:
if(!$isValid) {
Source : http://bit.ly/1hxDmVR
Here is sample code for working with logical operators in PHP. Hope it will helpful:
<html>
<head>
<title>Logical</title>
</head>
<body>
<?php
$a=10;
$b=20;
if($a>$b)
{
echo " A is Greater";
}
elseif($a<$b)
{
echo " A is lesser";
}
else
{
echo "A and B are equal";
}
?>
<?php
$c=30;
$d=40;
//if(($a<$c)AND($b<$d))
if(($a<$c)&&($b<$d))
{
echo "A and B are larger";
}
if(isset($d))
$d=100;
echo $d;
unset($d);
?>
<?php
$var1=2;
switch($var1)
{
case 1:echo "var1 is 1";
break;
case 2:echo "var1 is 2";
break;
case 3:echo "var1 is 3";
break;
default:echo "var1 is unknown";
}
?>
</body>
</html>
I think the problem is that your $isValid variable can be changed many times in the loops and by the end of your code simply applies to the last value in your final loop.
You should set it to true initially and then only set it to false IF your validity check fails - not simply assign its value based on every single validity check.

PHP, does "else" always get processed?

I have a rough program sketched thusly:
if (condition){
//redirect to some page
}
else{
echo $some_var;
}
So when I test is and the condition is true, it does the redirect, but also throws notices that there are undefined variables $some_var (that are pulled from a DB and WON'T be defined if the condition is true).
So does the code continue to evaluate after the if? This is not what I've expected.
If you want to dig, here's the actual code (it's CodeIgniter, but it's mostly self-documenting) and the test case is a garbage "gift code" that's not in the DB, so that count_all_results WILL == 0. The notices thrown are that $uses is undefined.
$data['message'] = null;
//seeing if code is valid
$submitted_code = $_POST['code'];
$this->db->where('code', $submitted_code);
$this->db->from('codes');
if ($this->db->count_all_results() == 0){
$data['message'] = "This is not a valid gift code, sorry! You'll need to read our partner blogs, or listen to our favored Twitterers to find a valid code.";
$this->load->view('submission_form_view', $data);
}
else {
//seeing if code has any uses left
$this->db->where('code', $submitted_code);
$this->db->from('redemption_information');
$used_so_far = $this->db->count_all_results();
$this->db->select('uses');
$query = $this->db->get_where('codes', array('code' => $submitted_code));
foreach ($query->result() as $result)
{
$uses = $result->uses;
}
echo "Uses: $uses Used so far: $used_so_far <br />";
if ($uses <= $used_so_far) {
$this->load->view('over_used_view');
}
else
{
//these values are auto-escaped, so no worries on SQL injection
if ($this->db->insert('redemption_information', $_POST)) {
$data['message'] = "Your order has been taken, thanks for your interest!";
$this->load->view('success_view', $data);
}
else {
$data['message'] = "There was an error with your order. Please try again.";
$this->load->view('submission_form_view', $data);
}
}
}
There's a difference between parsing and evaluation. The notices you're getting are parse notices (it's parsing the variable in the else statement and not seeing a previous assignment, so it throws a notice), but the statement isn't actually evaluated if the if condition is true.
The else block will always be executed if the preceeding if block is false
You can test is isset($uses) to avoid the warning and instantiate a default value for $uses
Edit
Create a default value for $uses:
$uses= null;
foreach ($query->result() as $result)
{
$uses = $result->uses;
}

Categories