Conditional Statement confusion PHP - php

EDIT : Damn... It was all about Path to the file and somehow I didn't thought about restructuring :| thanks to #Machavity I found the problem.
What is wrong with this code ?
If $foo is set and file exist file_exist() result should be 1.
else if $foo is set but file does not exist file_exist() result should be 2.
else result should be 3.
But I am only getting result 2 for all the three conditions. There gotta be something wrong with the second part of the elseif.
if ( isset ( $foo ) && file_exists ( 'bar.php' ) )
{
echo '1';
}
else if ( isset ( $foo ) && ( ! file_exists ( 'bar.php' ) ) )
{
echo '2';
}
else
{
echo '3';
}

Normally I don't like wrapping but try restructuring like this. This way you have a better idea of what's failing
if(isset($foo)) {
if(file_exists('bar.php')) {
echo '1';
} else {
echo '2';
}
} else {
echo '3';
}

Related

Check for multiple null isset values

I am checking if two values are null. If both are null I want to return false, if either or both are not null, I want to return true.
My current code returns true only when both are not null but I want it to return true when either or not null.
// check if both null
if (!isset($myarray['dataone'], $myarray['datatwo']))
{
echo 'false';
);
} else {
echo 'true';
);
}
return $emptytabs;
For that you can use relational operators. AND (&&) OR (||)
By using AND (&&) operators.
if ( (!isset($myarray['dataone']) || (!isset$myarray['datatwo'] ))
{
echo 'false';
}
else
{
echo 'true';
}
By using OR ( || ) operators.
if (isset($myarray['dataone'] && isset$myarray['datatwo'])
{
echo 'false';
}
else
{
echo 'true';
}
// check if both null
if ( !isset($myarray['dataone']) && !isset($myarray['datatwo'])) {
echo 'false';
} else {
echo 'true';
}
// check if one or both are null
if ( !isset($myarray['dataone']) || !isset($myarray['datatwo'])) {
echo 'false';
} else {
echo 'true';
}
// check if both null
if ( !isset($myarray['dataone'], $myarray['datatwo']) )
{
echo 'false';
} else {
echo 'true';
}
return $emptytabs;
this approach you provided is totally true , but it only return true if all the provided parameters are set according to php documentations .
so your code should works correctly . except you have unwanted parentheses that should deleted
The simplest way is to use the OR (||) operator. You want to show 'true' if one thing is set OR another thing is set. Just say that with code.
if ( isset($myarray['dataone']) || isset($myarray['datatwo']) ) {
echo 'true';
} else {
echo 'false';
}
Using the AND operator adds pointless complexity by checking that both of the two things are not set in order for it to show 'false'. That's not an intuitive way to think about it, so it doesn't make sense to write the code that way.
DISCLAIMER: This answer is opinionated.

How to check if any variables are set?

checking if all are set
if(
isset($var1) &&
isset($var2) &&
isset($var3)
){}
can be re-written as
if(isset($var1,$var2,$var3)){}
but what's the syntax for if any are set?
if(
isset($var1) ||
isset($var2) ||
isset($var3)
){}
Looks ugly; is there any better way to write this?
You have to pass strings instead of the variables, but for fun:
if(compact('var1', 'var2', 'var3')) {
echo 'one or more is set';
} else {
echo 'none are set';
}
I guess one could write a simple function to use, but there's probably a cleaner way.
function anyset(...$vars){
foreach($vars as $var){
if(isset($var)){
return true;
}
}
return false;
}
if(anyset($var1,$var2,$var3)){}

php more readable if statement

I am just wondering if there is better way to solve my situatuion:
I have 6 independent variables to check. But if any of conditions is true it shouldnt check other. Normally I would write:
if (cond1 ) {
statement
} else {
if ( cond2 ) {
statement
} else {
if (cond3) {
statement
} else {
...
}
}
}
Surely you would admit it doesnt look good or it is not easy to read although it works. Do you know any other ways to write such if statement maybe using other notation or functions (switch? while?)
Yes, you can do
if (cond1 ) {
statement
} elseif ( cond2 ) {
statement
} elseif ( cond3 ) {
statement
}
See documentation
A more stylish way:
if(cond1):
statement1
elseif(cond2):
statement2
elseif(cond3):
statement3
elseif(cond4):
statement4
elseif(cond5):
statement5
elseif(cond6):
statement6
endif;
This is how you do it with a switch():
$a = 10;
$b = 100;
switch(true){
case ($a > $b):
echo 'a is bigger than b';break;
case ($b > $a):
echo 'b is bigger than a';break;
}
if (cond1 ) {
statement
} else {
if ( cond2 ) {
statement
} else {
if (cond3) {
statement
} else {
...
}
}
}
Change to:
if (Cond1){
}elseif (cond2){
}elseif (cond3){
}

checking if condition for 0 value

in if condition i want to check
if(isset($_GET['q']))
{
echo "ok";
}
esle
{
echo "not ok";
}
when $_GET['q']=0 if send me in else part.
But i want to go in if .
if $_GET['q'] have any value even for 0 if should print ok
any help pls ?
This is what isset does. Try:
$x["q"] = 0;
var_dump(isset($x["q"]));
You will get true. If you think isset() returns false on 0 you are looking at the wrong place, look for a bug elsewhere.
0 is not null http://php.net/manual/en/function.isset.php
You might need something like this considering the value you want is integer
if(isset($_GET['q']) && intval($_GET['q']) > 0 )
{
echo "ok";
}
else
{
echo "not ok";
}
perhaps array_key_exists() would be more appropriate.
if ( array_key_exists( 'q', $_GET ) ) ...
I think this is the correct one...
if(array_key_exists('q', $_GET)){
echo "ok";
}
else{
echo "not ok";
}

What's the difference between if and elseif?

This should be a simple question. I have a simple if/else statement:
<?php
// TOP PICTURE DEFINITIONS
if ( is_page('english') ) {
$toppic = 'page1.png';
}
if ( is_page('aboutus') ) {
$toppic = 'page1.png';
}
if ( is_page('newspaper') ) {
$toppic = 'page1.png';
}
else {
$toppic = 'page1.png';
}
?>
Is there a difference from ^^^ to this:
<?php
// TOP PICTURE DEFINITIONS
if ( is_page('english') ) {
$toppic = 'page1.png';
}
elseif ( is_page('aboutus') ) {
$toppic = 'page1.png';
}
elseif ( is_page('newspaper') ) {
$toppic = 'page1.png';
}
else {
$toppic = 'page1.png';
}
?>
I should mention that this is going into Wordpress. And until now, I've used the first part (no elseif, just a series of 'ifs'), and it works. I was just curious to know what the difference was.
Thanks!
Amit
Yes. If a condition in an if/else control is satisfied, the rest of the checks will be omitted. else if is just a nested if inside an else!
if ( is_page('english') ) { // if true, other statements are skipped
$toppic = 'page1.png';
}
elseif ( is_page('aboutus') ) {
$toppic = 'page1.png';
}
elseif ( is_page('newspaper') ) {
$toppic = 'page1.png';
}
else {
$toppic = 'page1.png';
}
But in a series of ifs, all of them will be tested.
if ( is_page('english') ) {
$toppic = 'page1.png';
}
if ( is_page('aboutus') ) { // will be tested no matter what the outcome
// of the previous if statement was
$toppic = 'page1.png';
}
if ( is_page('newspaper') ) { // the same here
$toppic = 'page1.png';
}
else {
$toppic = 'page1.png';
}
So, if you're checking a property such as parity of a number, it's either odd or even, why do you want to bother checking other conditions if one is satisfied. It's a waste of resources. Therefore, the following code is much better
if(number_is_odd) {
}
else { // if it's not odd, it's even for sure
}
than
if(number_is_odd) {
}
if(!number_is_odd) {
}
Because the former checks the condition once whilst the latter does it twice. The same thing goes for conditions with more than two states.
The first method will check against every condition, whether they are true or false.
The second method will check against every condition until one is true, and then ignores the rest.
In your first block, every comparison in your block is executed. Also, toppic will always be assigned the value in is_page('newspaper') or the value in is_page('newspaper')'s else statement. This happens because the last if statment is always evaluated. Even if one of the previous if statements evaluated to true, you'll end up in the else block. To test this, try this code...
<?php
// TOP PICTURE DEFINITIONS
if ( is_page('english') ) {
$toppic = 'english.png';
}
if ( is_page('aboutus') ) {
$toppic = 'aboutus.png';
}
if ( is_page('newspaper') ) {
$toppic = 'newspaper.png';
}
else {
$toppic = 'finalelse.png';
}
?>
You'll always end with either 'newspaper.png' or 'finalelse.png'.
<?php
if ( 3 > 1 ) {
echo "This will be printed.";
}
if ( 3 > 2 ) {
echo "This will be printed too.";
}
if ( 3 > 3 ) {
echo "This will NOT be printed.";
}
else {
echo "This WILL be printed.";
}
?>
but with elseif:
<?php
if ( 3 > 1 ) {
echo "This will be printed.";
}
elseif ( 3 > 2 ) { /* This condition will not be evaluated */
echo "This will NOT be printed";
// because it's on the ELSE part of the previous IF
}
elseif ( 3 > 3 ) { /* This condition will not be evaluated either */
echo "This will NOT be printed.";
}
else { /* This ELSE condition is still part of the first IF clause */
echo "This will NOT be printed.";
}
?>
So you should use ELSEIF, because otherwise $toppic will always result on either 'newspaper.png', wich should be right, or 'finalelse.png' wich could be right or wrong, because it will overwrite the previous conditional clauses.
I hope you'll find this helpful.
It's not always just a question of efficiency. If you are toggling something, it is essential to use else if and not just if
Let's say we are toggling the variable $computerOn
if ($computerOn == true) {
$computerOn = false;
}
if ($computerOn == false) {
$computerOn = true;
}
In the case above your $computerOn will always be true. If it's true, it is set to false. After this, we check if it is false, which it now must be independent of initial conditions, so it is now set to true.
On the other hand the code below will toggle $computerOn:
if ($computerOn == true) {
$computerOn = false;
} elseif ($computerOn == false) {
$computerOn = true;
}
Now we only check whether $computerOn is false if it was not initially true. Hence we have a toggle.
If things get more complicated, you might have to use multiple elseifs. It's important to recognize when logic dictates that elseif is a must vs an option.
The biggest difference between the two is that the very last else block will be called whenever is_page('newspaper') returns false. In this case, it means just about every time the script runs. In this case, it's not a big deal, since you're only setting a variable, and it's the same value as everything else. But, if it were different, you would have a very frustrating bug to track down!
Besides that, if you use separate if statements, the condition for each if is evaluated every time. Again, in this case, it's (probably) not a big deal. But, if the condition was, say...
if(delete_file('foo.png')) {
....
}
if(delete_file('bar.png')) {
....
}
if(delete_file('baz.png')) {
....
}
else {
....
}
Well, you should be able to see where this is going ;) If you use elseif, it will stop trying to evaluate once it gets a true. And, the else will only be called if nothing else is true.
The answer is simple:
if(a==1){
b
}
elsif(b==1){
c
}
equals to
if(a==1){
b
}
else{
if(b==1){
c
}
}
This is the same as
if(a==1){
b
}
if(b==1){
c
}
if it is not possible that a==1 and b==1 at the same time. Although when both if statements can be true, when b and c can be executed. This would not be possible if you use elsif there, because b==1 would only be checked if a!=1!
Use elseif wisely can save you a bunch of time since the parser doesn't need to evaluate all the conditions.

Categories