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";
}
Related
is it any way to stop this repeated data.
if ($employees_csa[0]->csa_taken == 2 && $employees_csa[1]->csa_taken == 2 && $employees_csa[2]->csa_taken == 2 && $employees_csa[3]->csa_taken == 2 && $employees_csa[4]->csa_taken == 2 && $employees_csa[5]->csa_taken == 2 && $employees_csa[6]->csa_taken == 2 && $employees_csa[7]->csa_taken == 2) {
echo "data";
}
i tried for key range(0 , 8)
like this
foreach (range(0, count($employees_csa)) as $number) {
if ($employees_csa[$number]->csa_taken == 2) {
echo "data";
}
}
i tried that way not get any succes. i any another way to write easy condition.
You can loop arrays out of the box:
$all_taken = true;
foreach ($employees_csa as $employee) {
if ($employee->csa_taken != 2) {
$all_taken = false;
break;
}
}
if ($all_taken) {
echo 'data';
}
Another approach would be array_reduce() but this doesn't abort looping when there's already an answer:
$all_taken = array_reduce($employees_csa, function ($all_taken, $employee) {
if ($employee->csa_taken != 2) {
return false;
}
return $all_taken;
}, true);
if ($all_taken) {
echo 'data';
}
Alternatively, you could do it like this using array_column to pull out all the csa_taken properties, then reducing to 1 item if they are all the same with array_unique() and then checking that the same value is the expected number 2 with reset().
$csa_taken = array_column($employees_csa, 'csa_taken');
if (reset($csa_taken) === 2 && count(array_unique($csa_taken)) === 1) {
echo 'data';
}
Reusable function version: https://3v4l.org/4kYiE
A simple for-loop could work
$condition_met=true;
for($i=0;$i<8;++$i){
if( $employees_csa[$i]->csa_taken != 2){
$condition_met=false;
break;
}
}
if($condition_met===true){
//success
}
else{
//fail
}
A simple method could be done like
foreach($employees_csa as $singleEmployee){
if($singleEmployee->csa_taken == 2){
echo "data";
}
}
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.
i want to check two string in if condition equal or not but it is give me return true whats the problem please check my code.
$if = "(1 == 2)";
if($if){
echo 'hi';
}
see my code above.. it always return hi.. what i was done wrong please help me.
its return only hi.. i have many condition store in if variable but my first condition not fulfill so i want it now.. please suggest me.
my full code is here..
$if = "(1 == 2)";
if($location_search != ''){
$if .= " && ('."$location_search".' == '."$get_city".')";
}
if($location_state != ''){
$if .= " && ('."$location_state".' == '."$get_state".')";
}
if($location_bedrooms != ''){
$if .= " && ('."$location_bedrooms".' == '."$get_bedrooms".')";
}
if($location_bathrooms != ''){
$if .= ' && ('."$location_bathrooms".' == '."$get_bathrooms".')';
}
if($location_type != ''){
$if .= ' && ('."$location_type".' == '."$get_type".')';
}
if($location_status != ''){
$if .= " && ('".$location_status."' == '".$get_status."')";
}
if($if){
echo 'hi';
}
i added this code but always return tru and print hi. please help me.
Collect all of your variables in one array and go through it with foreach checking everyone. If one of variables is empty, assign false to your if variable. Will write code later, when will be next to computer.
Your variable $if is a declared as a string due to the double quotes. How about this
$a = 1;
$b = 2;
if ($a == $b) {
// When $a equals $b
echo "hi";
} else {
// When $a doesn't equal $b
$if is a string, and not null. In PHP this means it's true. I think if you remove the quotes, it should instead evaluate the expression to false.
Remove the double quotes here " (1 == 2)"
You can remove quotes (with quotes it's a normal string), but keep in mind that this is bad approach and should not be used like this.
Working code:
$if = (1 == 2); // evaluates to true
if($if) {
// code
}
I want to check the GET variables are not empty, I tried ways but they didn't work.
So I had the code like this:
$u = isset($_GET["u"]);
$p = isset($_GET["p"]);
if ($u !== "" && $p !== "") {
//something
} else {
//do something
}
The I checked the code by sending create.php?u=&p=, but the code didn't work. It kept running the //do something part. The I tried:
echo $u;
echo $p;
It returned 1 and 1. Then I changed it to:
if ($u !== 1 && $p !== 1 && $u !== "" && $p !== "") {
//something
} else {
//do something
}
But it continued to run //do something.
Please help.
You can just use empty which is a PHP function. It will automatically check if it exists and whether there is any data in it:
if(empty($var))
{
// This variable is either not set or has nothing in it.
}
In your case, as you want to check AGAINST it being empty you can use:
if (!empty($u) && !empty($p))
{
// You can continue...
}
Edit: Additionally the comparison !== will check for not equal to AND of the same type. While in this case GET/POST data are strings, so the use is correct (comparing to an empty string), be careful when using this. The normal PHP comparison for not equal to is !=.
Additional Edit: Actually, (amusingly) it is. Had you used a != to do the comparison, it would have worked. As the == and != operators perform a loose comparison, false == "" returns true - hence your if statement code of ($u != "" && $p != "") would have worked the way you expected.
<?php
$var1=false;
$var2="";
$var3=0;
echo ($var1!=$var2)? "Not Equal" : "Equal";
echo ($var1!==$var2)? "Not Equal" : "Equal";
echo ($var1!=$var3)? "Not Equal" : "Equal";
echo ($var1!==$var3)? "Not Equal" : "Equal";
print_r($var1);
print_r($var2);
?>
// Output: Equal
// Output: Not Equal
// Output: Equal
// Output: Not Equal
Final edit: Change your condition in your if statement to:
if ($u != "" && $p != "")
It will work as you expected, it won't be the best way of doing it (nor the shortest) but it will work the way you intended.
Really the Final Edit:
Consider the following:
$u = isset($_GET["u"]); // Assuming GET is set, $u == TRUE
$p = isset($_GET["p"]); // Assuming GET is not set, $p == FALSE
Strict Comparisons:
if ($u !== "")
// (TRUE !== "" - is not met. Strict Comparison used - As expected)
if ($p !== "")
// (FALSE !== "" - is not met. Strict Comparison used - Not as expected)
While the Loose Comparisons:
if ($u != "")
// (TRUE != "" - is not met. Loose Comparison used - As expected)
if ($p != "")
// (FALSE != "" - is met. Loose Comparison used)
You need !empty()
if (!empty($_GET["p"]) && !empty($_GET["u"])) {
//something
} else {
//do something
}
Helpful Link
if ($u !== 1 && $p !== 1 && $u !== "" && $p !== "")
why are you using "!==" and not "!=".
to always simplify your problem solve the logic on paper once using the runtime $u and $p value.
To check if $_GET value is blank or not you can use 2 methods.
since $_GET is an array you can use if(count($_GET)) if you have only u and p to check or check all incoming $_GET parameters.
empty function #Fluffeh referred to.
if($_GET['u']!=""&&$_GET['p']!="")
Hope it helps thx
In you code you should correctly check the variable existence like
if ($u != NULL && $p != NULL && $u != 0 && $p != 0) {
//something
} else {
//do something
}
Wow! I was so dumb... isset returns a boolean. I fixed my problem now. Thank you for answering anyway :)
This fixes:
$u = $_GET["u"];
$p = $_GET["p"];
Is this a possible function?
I need to check if a variable is existent in a list of ones I need to check against and also that cond2 is true
eg
if($row['name'] == ("1" || "2" || "3") && $Cond2){
doThis();
}
It's not working for me and all I changed in the copy paste was my list and the variable names
if(in_array($row['name'], array('1', '2', '3')) && $Cond2) {
doThis();
}
PHP's in_array() docs: http://us.php.net/manual/en/function.in-array.php
You're lookin for the function in_array().
if (in_array($row['name'], array(1, 2, 3)) && $cond2) {
#...
if (in_array($name , array( 'Alice' , 'Bob' , 'Charlie')) && $condition2 ) {
/* */
}
use in_array function
if(in_array($row['name'], array(1,2,3)) && $cond2){
do ...
}
$name = $row['name'];
if (($name == "1" || $name == "2" || $name == "3") && $cond2)
{
doThis();
}
I have something simpler than that, if it's still possible...
if(strpos("1,2,3", $row['name']) !== false) && $Cond2) {
doThis();
}