Placement of Else in a nested If - php

I am a PHP noob working through the tutorials and I found an issue with nested If Else that I don't understand. I have an outer if with a series of inner if's. And, I have an else I wanted associated with the outer if. My original code never executed the else, which should occur if the outer if was false. The original code was:
if (!($result["name"] & $result["age"] & $result["email"]))
{
if (!$result["name"])
{
echo("Name must be supplied.<br>");
}
if (!$result["age"])
{
echo("Age must be a number between 1 and 120.<br>");
}
if (!$result["email"])
{
echo("E-Mail is not valid.<br>");
}
}
else
{
echo("User input is valid.<br/>");
}
As I said, the else was never executed. However, I moved the else inside the brackets and it worked. The working code is:
if (!($result["name"] & $result["age"] & $result["email"]))
{
if (!$result["name"])
{
echo("Name must be supplied.<br>");
}
if (!$result["age"])
{
echo("Age must be a number between 1 and 120.<br>");
}
if (!$result["email"])
{
echo("E-Mail is not valid.<br>");
}
else
{
echo("User input is valid.<br/>");
}
}
This seems to be wrong to me. Probably just some noob mistake but I cannot figure it out. Thanks for your help...RG

Use AND comparison operator or && comparison operator instead of & bitwise operator.
For a quick review of PHP operators go here

Replace this:
if (!($result["name"] & $result["age"] & $result["email"]))
with this
if (!($result["name"] && $result["age"] && $result["email"]))
Its two & signs not only one.

on your first if . if you want to execute it
if your name,age and email is empty or not set
you need atleast to put ! on every $result[] and change your & to &&
if (!($result["name"] && !$result["age"] && !$result["email"]))
try to use this code..

Related

Validating an if statement with two conditions

I'm trying to validate a form. The form has a simple if statement. What is wrong with this please? The browser says: Parse error: syntax error, unexpected '&&' . Both the variables being checked are separate fields. They must both be numbers & not empty.
if (isset($_POST["submit"])) {
if(empty($numberwelds)) && (empty($conwelds)) {
echo " One or both of the numbers are empty ";
} else if(!is_numeric($numberwelds)) && (!is_numeric($conwelds)) {
echo "Data entered was not numeric";
} else {
echo "it passed";
}
}
I'm still getting ' one or both of the numbers are empty', even if they both are numbers. My new code:
if (isset($_POST["submit"])) {
if(empty($numberwelds) || empty($conwelds)) {
echo " One or both of the numbers are empty ";
} else if(!is_numeric($numberwelds) || !is_numeric($conwelds)) {
echo "one or both of them is not a number";
} else {
echo "it passed";
}
}
Thank-you
Your problem is on the lines where you have;
if(empty($numberwelds)) && (empty($conwelds)) {...
and,
} else if(!is_numeric($numberwelds)) && (!is_numeric($conwelds)) {
you are basically trying to create an if statement of the form;
if(stuff in here) && (stuff in here){..
This is a syntax error because if statements need to be followed immediately by a bracketed control flow, and in your example you have an if statement followed by &&.
All you need to do is add some more brackets to make a correct if statement, for example;
use
if((stuff in here) && (stuff in here)){...
instead of
if(stuff in here) && (stuff in here){..
If you want your error output One or both of the numbers are empty to be accurate, you have to use || and not &&
What's happening is even if one of the options is empty, the if statement is ignored. And && means both statements must be true. An || means the either-or OR both must be true.
As far as the syntax error, the other answered solved it for you.

PHP: Multiple conditions with NOT Equal (!=) operator is not working [duplicate]

This question already has answers here:
PHP if not equal(!=) and or (||) issue. Why doesnt this work?
(6 answers)
Closed 4 years ago.
Hope u people will be fine.
I’m working on a following code in which i want to use multiple php if conditions with multiple not operators (example is below), but when i execute following php code, it always returns true (mean content in always parenthesis always executed) even no condition is true.
I want to ask what is the problem in following code. Is there any specific syntax or rule for using multiple != operator in php conditions. And i am amazed to see that if i use following code by replacing != operator with == operator it is working fine.
if( $ext!="exe" || $ext!="html" || $ext!="htm" || $ext!="js" || $ext!="iso" || $ext!="zip" || $ext!="rar" )
{ // ececk extension
echo $ext."extension";
}
else{
echo "not match";
}
Waiting for your kind replies. and sorry for my bad english.
Better code:
$allowed = array('jpeg','png');
if(in_array($ext,$allowed)){
echo "Correct";
}
else {
echo "Wrong";
}
User XOR operator instead of OR as or checked all condition need to be identical while XOR return true if anyone from all is identical:
if(!($ext!=="exe") xor ($ext=="html")){ //Add more conditions
//each condition in new brackets & ! sign in start before all conditions
{ // ececk extension
echo $ext."extension";
}
else{
echo "not match";
}
Hope it will help

PHP validation function. Check for numeric and positive

Little confused about how to code this. User inputs numbers, then the validation checks to make sure it is numeric and positive. The user can also leave this field blank.
This is what i have so far, it just checks to see that something was inserted.
$error_blue = check_blue($phone);
if($error_blue !=''){
print "<p>Blue: $error_blue";
}
Is where the item is validated at the top of the page.
function check_blue($blue){
if(! is_numeric($blue)){
return'Please Enter a valid number for Blue.';
}}
Is where the function is.
Any help on what to do here would be much appriciated.
Something like this?
function check_blue($blue) {
if (is_numeric($blue) && $blue > -1) {
return 1;
}
else {
return 0;
}
}
if(!check_blue($phone)) {
return'Please Enter a valid number for Blue.';
}
See the demo
Assuming it's an integer you expect,
if ((int)$blue==abs($blue) || empty($blue)) $error = false;
else $error = true;
Then you use $error to decide what to do.
Everyone here was using if else. It is not that this is wrong, but just to show you another idea, which might be useful for other type of validation, take a look at validate filters :
http://www.php.net/manual/en/filter.filters.validate.php
For this purpose you might use FILTER_VALIDATE_INT
You might want to use something simple as
function check_blue($phone) {
return (empty($phone) || (is_numeric($phone) && $phone >= 0));
}
First check if the field is blank, nothing to do if it is.
If it is not blank it will be checked for numericality and to being greater or equal zero.

Coding style - how do I format a long if condition to make it readable

I have a long if condition as follows. There are two conditions that both have to not be met, for the statement to evaluate. I did have it as a one liner with a lot of && and ! but it became unreadable. I have tried splitting it into an if elsif else, which is more readable but doesn't read well, as the first if elsif blocks have no code in them.
What would be the best practice to tidy this code block?
if ($instructionObject->instruction=='nesting_grammar' && $instructionObject->match=='>'){ //if instruction is a '>' child indicator
//don't change the child depth
}else if ($instructionObject->instruction=='selector' && is_object($this->instructions[$key+1]) && $this->instructions[$key+1]->instruction == 'nesting_grammar' && $this->instructions[$key+1]->match == '>'){ //if instruction is a selector followed by a '>'
//don't change the child depth
}else{
$insertOffset += $childDepth;
unset($childDepth);
}
You can use "extract method" refactoring. Replace your conditions to new methods.
if ($this->isInstructionNestingGrammar($instructionObject)){
//don't change the child depth
}else if ($this->isIntructionSelect($instructionObject)){
//don't change the child depth
}else{
$insertOffset += $childDepth;
unset($childDepth);
}
In new methods put every compare to separate line.
P.S. Don't be afraid of long name of methods.
Just negate the conditions and skip the if and else if parts as the two initial conditions don't do anything...
if (
!($instructionObject->instruction=='nesting_grammar' &&
$instructionObject->match=='>')
|| !($instructionObject->instruction=='selector'
&& is_object($this->instructions[$key+1])
&& $this->instructions[$key+1]->instruction == 'nesting_grammar'
&& $this->instructions[$key+1]->match == '>')
) {
$insertOffset += $childDepth;
unset($childDepth);
}
Not directly answering your question, but what about something like:
if (my_check($instructionObject) || $instructionObject->instruction=='selector' && my_check($this->instructions[$key+1])) {
} else {
$insertOffset += $childDepth;
unset($childDepth);
}
function my_check($obj) {
return is_object($obj) && $obj->instruction == 'nesting_grammar' && $obj->match == '>';
}
-- you are basically doing the same thing twice, time to think about a function for that.
Personally if i'm going to span the check across multiple lines i lay it out similar to how i'd lay out a JavaScript object;
if (
great big long check line goes in here &&
another really long ugly check line goes in here too
) {
// Do this code
}
else if (
check 3 &&
check 4
) {
//Do this code
}
Pull out sub-expressions into variables. Pseudo-example:
flibjit = FlibjitManager.FlibjitInstance(this);
isFrob =
(flibjit.Froblocity >= FlibjitManager.FrobThreshold) &&
(flibjit.Type == FlibjitTypes.Frobby);
if (isFrob) {
// ...

PHP - If something is the case, do nothing

Is this a proper way to say: if something is the case, do nothing?
if ( ($hostNameInfo == $hostNameInput) && ($hostAddressInfo == $hostAddressInput) )
{
return;
}
Update:
I'm not inside a function. :(
So the return is just nonsense.
Here is more code:
//if the input fields are equal to database values, no need to update and waste resources,hence, do nothing:
if ( ($hostNameInfo == $hostNameInput) && ($hostAddressInfo == $hostAddressInput) )
{
//do nothing
}
//If, however, (they are NOT equal and) input fields are not empty:
elseif (!empty($hostNameInput) && (!empty($hostAddressInput)))
{
//do something.
}
Thanks in advance,
MEM
For do nothing you simply can type:
function relax() {
;
}
if (($hostNameInfo == $hostNameInput) && ($hostAddressInfo == $hostAddressInput)) {
relax();
}
Maybe you should do the opposite, do something if your condition is not verified
if($hostNameInfo != $hostNameInput || $hostAddressInfo != $hostAddressInput) {
// do something
}
I assume you're inside a function in which case it does what you expect, although multiple return statements within a function can lead to confusion and a lack of readability. (Apparently I was wrong.)
Instead, I prefer to let all conditional blocks (my description for the code between in the if's {...} block) contain the relevant code, i.e., write the conditional check in such a way that the total condition evaluates to true when additional processing (sub-flow) is needed:
if ($hostNameInfo != $hostNameInput || $hostAddressInfo != $hostAddressInput) {
// do stuff, else skip
}
Furthermore, you can extract the conditional statement in order to improve both readability and simplicity of control flow:
$hostInfoEqualsInput = ($hostNameInfo == $hostNameInput && $hostAddressInfo == $hostAddressInput);
if (!$hostInfoEqualsInput) {
...
}
UPDATE (based on updated question). Consider this instead:
$fieldsAreFilled = (!empty($hostNameInput) && !empty($hostAddressInput));
$hostInfoEqualsInput = ($hostNameInfo == $hostNameInput && $hostAddressInfo == $hostAddressInput);
if ($fieldsAreFilled && !$hostInfoEqualsInput) {
...
}
ERGO
Minimize branch rate and avoid empty blocks by writing conditions you want to be met, not all the exceptions you want to ignore (subjective).
You're talking about best practices here..
One of best practice things is that routine shall have single exit point, though it is widely discussed and is up to developer/style.
UPDATE:
New answer, since the question was changed:
Don't see any reason to add additional checks if the code should run only under some circustances. To make the code more readable, you should stuck to whatever you accept as easy-maintainable, like this (or something similar):
// Do something only if required
if (($hostNameInfo != $hostNameInput) || ($hostAddressInfo != $hostAddressInput)) &&
!empty($hostNameInput) && !empty($hostAddressInput))
{
echo 'place some code here';
}
A native do_nothing() function would be very nice and readable sometimes.
To avoid stressing alerts from syntax checkers & linters, that go crazy when you have an empty if block, I use:
echo(null);
The other possibility is to throw a new exception, which you can later catch in your application.
UPDATE: not inside the function this is probably a bad idea.

Categories