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.
Related
Disclaimer : the following is a bad practice (but it would be useful in a very, very specific use)
Is there a way to shorten (in a not-so-nice-way-but-shorter) if statements :
instead of :
if(5 == $foo){
$b = 98;
$c = 98 * $otherVariable;
//do something complex
doSomethingElse($b, $c);
}
This example would become shorter, even if it is formatted by an IDE.
It would become something like that (but this does not work):
(5 == $foo) && { $b = 98;
$c = 98 * $otherVariable;
//do something complex
doSomethingElse($b, $c);}
I suggest, you should opt for better readable code, but still if you want to do something different, you may go through below :
($foo == 5) && doSomethingElse(98, 98*$otherVariable);
OR
PHP Ternary Operator
($your_boolean) ? 'This is true' : 'This is false';
You can rewrite your if statement like below :
($foo == 5) ? doSomethingElse(98, 98*$otherVariable) : "";
// little shorter but not better readable
($foo != 5) ? : doSomethingElse(98, 98*$otherVariable);
Test Results:
$ cat test.php
<?php
function aa(){ echo "123\n"; }
$foo = 5;
// this will not call aa()
($foo == 4) && aa() ;
// this will call aa()
($foo == 5) && aa() ;
?>
$ php test.php
123
if(5 == $foo) doSomethingElse(98, 98*$otherVariable);
Look out! The variables $b and $c are not available for further calculations!
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";
}
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"];
This is the code
$a = 'Rs 15.25';
if ( $a != '' && $a! = 0 ) {
echo "Inside If";
} else {
echo "Outside If";
}
actually I want to Print "Inside If" so that's why I put $a='Some String Value'. But it always prints "Outside If". Then I changed my code to
$a = 'Rs 15.25';
if ( $a != '' && $a != '0' ) {
echo "Inside If";
} else {
echo "Outside If";
}
I have just added single quotes to 0. Then i got the exact output as i want. But I didn't understand why this happens.
So please help me with this.
PHP does weak type comparison, that is, it converts both operands to the same type before doing the actual comparison.
If one of the operands is a number, the other one is converted to a number as well. If the second operand is a string and contains no digits, it is silently converted to the number 0.
To avoid this whole issue, use string type checking with the operator !== (=== for equality).
if($a !== '' && $a !== 0) {
echo "Inside If";
} else {
echo "Outside If";
}
First of all you when you have multiple conditions on an if statement you should always enclose each of them within brackets
So first thing you should do is to change your code to
$a='Rs 15.25';
if(($a!='') && ($a!='0'))
{
echo "Inside If";
}else
{
echo "Outside If";
}
In PHP 0 = FALSE, 1 = TRUE.
if($a != 0) -> if($a != FALSE)
if $a = 'Rs 15.25', $a != false and $a not empty, then you have echo "Outside If";
Is there a function to check both
if (isset($var) && $var) ?
The empty() function will do the job.
Use it with the not operator (!) to test "if not empty", i.e.
if(!empty($var)){
}
You may use the ?? operator as such:
if($var ?? false){
...
}
What this does is checks if $var is set and keep it's value. If not, the expression evaluates as the second parameter, in this case false but could be use in other ways like:
// $a is not set
$b = 16;
echo $a ?? 2; // outputs 2
echo $a ?? $b ?? 7; // outputs 16
More info here:
https://lornajane.net/posts/2015/new-in-php-7-null-coalesce-operator
there you go. that should do it.
if (isset($var) && $var)
if (! empty($var))
It seems as though #phihag and #steveo225 are correct.
Determine whether a variable is considered to be empty. A variable is
considered empty if it does not exist or if its value equals FALSE.
empty() does not generate a warning if the variable does not exist.
No warning is generated if the variable does not exist. That means
empty() is essentially the concise equivalent to !isset($var) || $var
== false.
So, it seems !empty($var) would be the equivalent to isset() && $var == true.
http://us2.php.net/empty
Try the empty function:
http://us2.php.net/empty
isset($a{0})
isset AND len is not 0 seems more reliable to me, if you run the following:
<?php
$a=$_REQUEST['a'];
if (isset($a{0})) { // Returns "It's 0!!" when test.php?a=0
//if (!empty($a)) { // Returns "It's empty!!" when test.php?a=0
echo 'It\'s '.$a;
} else { echo 'It\'s empty'; }
?>
$a = new stdClass;
$a->var_false = false;
$a->var_true = true;
if ($a->notSetVar ?? false) {
echo 'not_set';
}
if ($a->var_true ?? false) {
echo 'var_true';
}
if ($a->var_false ?? false) {
echo 'var_false';
}
This way:
if (($var ?? false) == true) {
}
I am amazed at all these answers. The correct answer is simply 'no, there is no single function for this'.
empty() tests for unset or false. So when you use !empty(), you test for NOT UNSET (set) and NOT FALSE. However, 'not false' is not the same as true. For example, the string 'carrots' is not false:
$var = 'carrots'; if (!empty($var)){print 1;} //prints 1
in fact your current solution also has this type problem
$var = 'carrots'; if (isset($var) && $var){print 1;} //prints 1
as does even this
$var = '1.03'; if (isset($var) && $var == true){print 1;} //prints 1
in fact... if you want to do as you described exactly, you need:
$var = 'carrots'; if (isset($var) && $var === true){print 1;} //Note the 3 Equals //doesn't print 1
I suppose the shortest valid way to test this case is :
if (#$var === true){ print 1;}
But suppressing errors for something like this is pretty awful practice.
Don't know if an exact one already exists, but you could easily write a custom function to handle this.
function isset_and_true($var) {
return (isset($var) && $var == true) ? true : false;
}
if (isset_and_true($a)) {
print "It's set!";
}
Check if the variable is set, and true. Ignore warning message
if(#!empty($foo))