If statement within an if statement - php

How do I put an if statement within an if statement? Right now it's like this;
<?php
if($var1===$var2)
{
if($condition1 > 0)
{
*lots of code here*
}
}
else
{
*lots of code here again*
}
}
?>
Meaning that I want $condition1 to be bigger than 0 IF $var1 does not match $var2. But as it stands I am duplicating the "lots of code part" so I just want to;
if($var1!=$var2){ -apply if statement- }
*lots of code here*
if($var1!=$var2){ -close if statement- }
But how?

<?php
$a = ($var1 === $var2);
$b = ($condition1 > 0);
if (!$a || $b)
{
*lots of code here*
}
?>

You have the right way of combining two if statements. However, you want to run lots of code either when var1 equals var2 or when condition1 is bigger than 0. You can write that like this:
<?php
if ($var1===$var2 || $condition1 > 0)
{
*lots of code here again*
}
?>
The || operator means 'or'.

Maybe i don't get it but i'd do it like this:
if($var1 === $var2 || $condition1>0){
//lots of code here
}else{
}
EDIT - maybe you wan't this - it reads if var1 is equal to var 2 OR if var1 is not equal to var2 and condition1>0 do lots of code
if($var1 === $var2 || ($var1 !== $var2 && $condition1>0)){
//lots of code here
}else{
}

Related

Can ($a == 1 && $a == 2 && $a == 3) ever evaluate to true?

Similar to this question here which was intended for javascript, it has spawned off numerous spin-offs for various different languages. I'm curious if the following can ever evaluate to true in PHP:
($a == 1 && $a == 2 && $a == 3)
To follow up a bit more, it seems simply setting $a = true will yield the desired result (This was not the case for javascript, due to the way type casting works in both languages). A few answers (in javascript) worked with === as well, so in PHP with typechecking (===), can the following ever yield true?
($a === 1 && $a === 2 && $a === 3)
I just tried this:
$a = true;
echo ($a == 1 && $a == 2 && $a == 3);
and it echoed 1.
Because of the type casting and not type checking, 1, 2, 3 will be treated as true when compared to a boolean value.
Answer to the edit: No it can't be done.
Hackish method which #FrankerZ commented about:
Zero byte character = 0xFEFF
http://shapecatcher.com/unicode/info/65279
http://www.unicodemap.org/details/0xFEFF/index.html
$var  = "1";
$var = "2";
$ var = "3";
echo ($var  === "1" && $var === "2" && $ var === "3") ? "true" : "false";
This code runs with this character because the name $ var and $var  seems to be valid for the PHP compiler and with the appropiate font, it can be hidden. It can be achieved with Alt + 65279 on Windows.
Whilst not strictly in keeping with the question, this can be done if the ints are wrapped in quotes:
<?php
class A {
private static $i = 1;
public function __toString()
{
return (string)self::$i++;
}
}
$a = new A();
if($a == '1' && $a == '2' && $a == '3') {
echo 'yep';
} else {
echo 'nope';
}
I can't think of a case where strict comparison would ever yield true. === operator compares the types first, so there's no way to use any magic method wizardry.
For curiosity the closest i could get is to slightly modify the setting and hack the variable in a tick function. Since ticks are only incremeted per statement, we have to break the comparison to multiple statements for this to work.
$a = 1;
register_tick_function(function () use (&$a) {
++$a;
});
declare(ticks = 1) {
$a === 1 or exit(1);
$a === 2 or exit(1);
$a === 3 or exit(1);
}
echo "a = $a\n";
Try it online.

PHP IF Statement - Two Variables Not Working

I have an IF statement and I need to check two variables, then execute the action if either of the variables are false.
I know I can use the OR (||) statement however for some reason it is not working. I am in the process of learning PHP so it's probably a syntax error on my behalf.
If I create the if statement with only one (either) variable, it works fine:
<?php if ($var1 == false) { do whatever...} ?>
However when I try to check two, neither of the variables seem to be checked. I have tried different syntax variations but nothing works:
<?php if (($var1 == false) || ($var2 == false)) { do whatever...} ?>
<?php if (($var1 == false) OR ($var2 == false)) { do whatever...} ?>
<?php if ($var1 == false || $var2 == false) { do whatever...} ?>
<?php if ($var1 == false OR $var2 == false) { do whatever...} ?>
Can someone please point out what my error is?
Thanks!
EDIT: Including the actual code.
<?php $member = $members_template->member; $bpmember = bp_get_member_user_id(); ?>
<?php $membersearchinclude = xprofile_get_field_data( 'Exclude yourself from website search results?', $bpmember ); ?>
<?php $adminsearchinclude = xprofile_get_field_data( 'Exclude From Search Results', $bpmember ); ?>
<?php if (($adminsearchinclude == false) || ($membersearchinclude == false)) { ?>
This is extracting the xprofile field state from two different checkboxes in BuddyPress. I am checking if either of the checkboxes are false, then executing code.
I have managed to solve the issue.
It seems my logical operators needed changing:
if ((!$adminsearchexclude) && (!$membersearchexclude))
I am sure if I posted the entire code one of you would have got it. This is a sensitive project at the moment at unfortunately posting the entire code wasn't an option.
Many thanks to everyone that chipped in especially #ChrisO'Kelly for the var dump snippets. You got me thinking in the right direction and I now have a new tool in my arsenal :)
THANK YOU ALL!!
I'm not sure what causing it to not run as expected because from my view its all valid. Try to post your code so we know the whole logic.
Try to use strict comparison.
$var1 = 0;
$var2 = 1;
// The echo will not be executed
if ($var1 === false || $var2 === false) {
echo "Strict comparison\n";
}
// The echo will be executed
if ($var1 == false || $var2 == false) {
echo "No strict comparison\n";
}
References:
http://php.net/manual/en/language.operators.logical.php
http://php.net/manual/en/language.operators.comparison.php

How do I add an if / else?

I am using the following code to pass a variable. if variable = a, do nothing.
I then want to check if variable = a, do nothing, if b, do nothing, else do something
<?
if($_GET['pageid'] == 'a'){
} else {
include('header_image.php');
}
?>
Above is the code I have working correctly for one vartiable.
How do I add an if / else?
if($_GET['pageid'] != 'a' && $_GET['pageid'] != 'b'){
//do smth
}
This is a comment - i want the formatting...
To do what you want:
if ($_GET['pageid'] == 'a') {
// do nothing for now
}
elseif ($_GET['pageid'] == 'b') {
// do some more nothing...
}
else { // we do something...
include('header_image.php');
}
You could combine the 'do nothing' tests as:
if ( $_GET['pageid'] == 'a'
|| $_GET['pageid'] == 'b') {
// do nothing for now
}
else { // we do something...
include('header_image.php');
}
I agree it reads better than the 'not equal and' tests. However, that is what 'programmers' use so it is worthwhile getting used to it.

Please help! How to express the cases in if clause?

I have string $a,$b,$c
I know if all of them not null express in this way:
if($a!="" && $b!="" && $c!="")
But if either 2 of them not null then go into the true caluse
if($a!="" && $b!="" && $c!=""){
** do the things here **
}else if(either 2 are not null){
**do another things here**
}
How to express it?
I would write a simple function like this to check:
function checkInput($var)
{
$nulls=0;
foreach($var as $val)
{
if(empty($val))
{
$nulls++;
}
}
return $nulls;
}
Then access it like this:
$inputs=array($a, $b, $c.... $z);
$nullCount=checkInput($inputs);
if($nullCount==0)
{
// All nulls
}
if($nullCount>2)
{
// More than 2 nulls
}
or for an one-off test, just pop the function into the actual if statement like this:
if(checkInput($inputs)>2)
{
// More than 2 nulls...
}
etc etc. You can then use the one function to check for any number of nulls in any number of variables without doing much work - not to mention change it without having to rewrite a long if statement if you want to modify it.
Other answers are good, but you can expand this to easily handle more variables:
$variables = array($a, $b, $c, $d, ....);
$howManyNulls = 0;
foreach($variables as $v){
if($v == ''){
$howManyNulls++;
}
}
if($howManyNulls == count($variables) - 2){
// do stuff
}
you can try this
if($a!="" && $b!="" && $c!="")
{
** do the things here **
}
else if(($a!="" && $b!="") || ($b!="" && $c!="") || ($a!="" && $c!=""))
{
**do another things here**
}
Try:
if($a!="" && $b!="" && $c!=""){
** do the things here **
}else if(($a!="" && $b!="") || ($a!="" && $c!="") || ($b!="" && $c!="")){
**do another things here**
}
$var[] = empty($a) ? 0:$a;
$var[] = empty($b) ? 0:$b;
$var[] = empty($c) ? 0:$c;
$varm = array_count_values($var);
if ($varm[0] === 0) {
//Code for when all aren't empty!
} elseif ($varm[0] === 1) {
//Code for when two aren't empty!
}
N.B; You may need to replace the 0 for a string/integer that will never crop up, if your variables are always strings or empty then 0 will do for this. The method for using bools within this would require more code.
$nullCount = 0
if($a!=""){ ++$nullCount; }
if($b!=""){ ++$nullCount; }
if($c!=""){ ++$nullCount; }
if($nullCount == 3){ // all are null
// do smth
}else if($nullCount == 2){ // only two are null
// do other
}
Just for fun, here's something potentially maintainable, should the list of arguments increase:
function countGoodValues(...$values) {
$count = 0;
foreach($values as $value) {
if($value != "") {
++$count;
}
}
return $count;
}
$goodValues = countGoodValues($a, $b, $c); // Or more... or less
if($goodValues == 3) {
// Do something here
}
else if($goodValues == 2) {
// And something else
}
Reference for the ... construct (examples #7 and #8 in particular) are available on php.net.
You can use double typecasting (to boolean, then to number) in conjunction with summing:
$count = (bool)$a + (bool)$b + (bool)$c;
if ($count == 3)
// ** do the things here **
else if ($count == 2)
//**do another things here**
There is also possible such solution:
<?php
$a= 'd';
$b = 'a';
$c = '';
$arr = array( (int) ($a!=""), (int) ($b!=""), (int) ($c!=""));
$occ = array_count_values($arr);
if ($occ[1] == 3) {
echo "first";
}
else if($occ[1] == 2) {
echo "second";
}
If you have 3 variables as in your example you can probably use simple comparisons, but if you have 4 or more variables you would get too big condition that couldn't be read.
if (($a!="") + ($b!="") + ($c!="") == 2) {
// two of the variables are not empty
}
The expression a!="" should return true (which is 1 as an integer) when the string is not empty. When you sum whether each of the strings meets this condition, you get the number of non-empty strings.
if (count(array_filter([$a, $b, $c])) >= 2) ...
This is true if at least two of the variables are truthy. That means $var == true is true, which may be slightly different than $var != "". If you require != "", write it as test:
if (count(array_filter([$a, $b, $c], function ($var) { return $var != ""; })) >= 2) ...
if($a!="" && $b!="" && $c!="") {
echo "All notnull";
} elseif(($a!="" && $b!="") || ($b!="" && $c!="") || ($a!="" && $c!="")) {
echo "Either 2 notnull";
}

Javascript; check if a variable is 1 or 0

I'm using a variable in Javascript which will be set via Php e.g. var usesInterview = <?php echo 1;?>
If not, then var usesInterview = <?php echo 0;?>
How best should I handle this in my code? There will be a If statement to check for the variable and determine the route to take.
I've tried using typeof() == 1 and when I set it to 0, it still carries out the routine as if it where 1.
Why not set it with javascript:
usesInterview = 1;
Even if you set it with PHP, you can check like this:
if (usesInterview === 1){
// variable is equal to 1
}
else if (usesInterview === 0){
// variable is equal to 0
}
Notice the === to check for both type as well as value. If you don't want to check for type, you need to use == like this:
if (usesInterview == 1){
// variable is equal to 1 or "1" or true
}
else if (usesInterview == 0){
// variable is equal to 0 or "0" or "" or false
}
You should avoid the later approach when you are sure about both type as well as value.
More Information:
http://w3schools.com/JS/js_comparisons.asp
There are so many ways you can do it... Ie
var usesInterview = <?php echo [0|1];?>
usesInterview ? goingTrueWay() : goingFalsegWay();
or
<?php echo [0|1];?> ? goingTrueWay() : goingFalseWay();
or something like this:
var waysCollection = {
0: function () {...} //routine for usesInterview == 0
1: function () {...} //routine for usesInterview == 1
}
waysCollection[<?php echo [0|1];?>]();
also you can use one of the early suggestion:
if (<?php echo [0|1];?>) {
// truthy branch
} else {
// falsy branch
}
BTW, if you want usesInterview to be a boolean, yes/no trigger, - use true/false not 0/1. Its easier to read and understand later. For ex
var usesInterview = <?php echo [false|true];?>
if (usesInterview) {
//do this if `true`
} else {
//do this if `false`
}
typeof will return the type of the value - "number" in this case. You're using a non-strict equality check (==) so "number" == 1 is true.
Just check the value, using type-strict equality operator (===):
if (usesInterview === 1) {
// do something
}
else if (usesInterview === 0) {
// do something else
}
Read more about JavaScript comparison operators at https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators.
When usesInterview is 1 it's truthy. So it's as simple as:
if (usesInterview) {
// truthy branch
} else {
// falsy branch
}

Categories