$a = true and false; //true
$b = true && false; //false
$c = (true and false); //false
$d = (true && false); //false
Why gives case 'a' true?
I thought that and and && has the same precedence but they don't.
As stated in the documentation, this is expected bahvior
// The constant true is assigned to $h and then false is ignored
// Acts like: (($h = true) and false)
$h = true and false;
http://php.net/manual/en/language.operators.logical.php
The constant true is assigned to $a and then false is ignored. It's all about operator precedences
Related
I want to compare the prefix of two strings to know if both are the same or different. Like if the format is the same.
Assume variable A contains a string with a prefix, i want to compare if the prefix of the value of variable A is the same with a string i.e if($variableA == "che-123456") do something else do something else. The prefix CHE is what i want to compare.
I have written universal function for your question. You can use it :
function comparePrefixes($a, $b, $separator = "-", $caseSensitive = false) {
if (!$caseSensitive) {
$a = strtolower($a);
$b = strtolower($b);
}
return substr($a, 0, strpos($a, $separator)) === substr($b, 0, strpos($b, $separator));
}
// Testcases
var_dump(comparePrefixes('chE-454545', 'ChE-78623')); //true
var_dump(comparePrefixes('chE.54545', 'ChE.78623', ".")); //true
var_dump(comparePrefixes('abcd-454545', 'abcd-78623')); //true
var_dump(comparePrefixes('chE-454545', 'ChE-78623', "-", true)); //false
var_dump(comparePrefixes('che-454545', 'che-78623', "-", true)); //true
// use case
$a = "che-1234";
$b = "che-5425";
if (comparePrefixes($a, $b)) {
echo "prefixes are equal";
}
RUN CODE
Is there an elegant way to check if multiple, but not all, conditions are true out of any given number of conditions?
For example, I have three variables: $a, $b, and $c.
I want to check that any two of these are true. So the following would pass:
$a = true;
$b = false;
$c = true;
But this wouldn't:
$a = false;
$b = false;
$c = true;
Also, I may want to check if 4 out of 7 conditions were true, for example.
I realise I can check each combination, but this would get more difficult as the number of conditions increased. Looping through the conditions and keeping a tally is the best option I can think of, but I thought there may be a different way to do this.
Thanks!
Edit: Thanks for all the great answers, they're much appreciated.
Just to throw a spanner in to the works, what if the variables weren't explicit booleans?
E.g.
($a == 2)
($b != "cheese")
($c !== false)
($d instanceof SomeClass)
A "true" boolean in PHP casts to a 1 as an integer, and "false" casts to 0. Hence:
echo $a + $b +$c;
...will output 2 if two out of the three boolean variables $a, $b or $c are true. (Adding the values will implicitly convert them to integers.)
This will also work with functions like array_sum(), so for example:
echo array_sum([true == false, 'cheese' == 'cheese', 5 == 5, 'moon' == 'green cheese']);
...will output 2.
You could put your variables in an array, and use array_filter() and count() to check the number of true values:
$a = true;
$b = false;
$c = true;
if (count(array_filter(array($a, $b, $c))) == 2) {
echo "Success";
};
I'd go for a method like the following:
if (evaluate(a, b, c))
{
do stuff;
}
boolean evaluate(boolean a, boolean b, boolean c)
{
return a ? (b || c) : (b && c);
}
What it says is:
If a is True, then one of b or c must be true too to comply with 2/3
True criterion.
Else, both b and c must be true!
If you want to expand and customise the conditions and the number of variables I'd go for for a solution like the following:
$a = true;
$b = true;
$c = true;
$d = false;
$e = false;
$f = true;
$condition = 4/7;
$bools = array($a, $b, $c, $d, $e, $f);
$eval = count(array_filter($bools)) / sizeof($bools);
print_r($eval / $condition >= 1 ? true : false);
Simply we evaluate the true's and we make sure that the % of True is equals or is better than what we want to achieve. Likewise you could manipulate the final evaluation expression to achieve what you want.
This should also work, and would allow you fairly easily to adjust to the numbers.
$a = array('soap','soap');
$b = array('cake','sponge');
$c = array(true,true);
$d = array(5,5);
$e = false;
$f = array(true,true);
$g = array(false,true);
$pass = 4;
$ar = array($a,$b,$c,$d,$e,$f,$g);
var_dump(trueornot($ar,$pass));
function trueornot($number,$pass = 2){
$store = array();
foreach($number as $test){
if(is_array($test)){
if($test[0] === $test[1]){
$store[] = 1;
}
}else{
if(!empty($test)){
$store[] = 1;
}
}
if(count($store) >= $pass){
return TRUE;
}
}
return false;
}
U can use while loop :
$condition_n = "x number"; // number of required true conditions
$conditions = "x number"; // number of conditions
$loop = "1";
$condition = "0";
while($loop <= $conditions)
{
// check if condition is true
// if condition is true : $condition = $condition + 1;
// $loop = $loop + 1;
}
if($condition >= $condition_n)
{
// conditions is True
}
else
{
// conditions is false
}
I think it is a little easy and short writing when you use operator "&" , "|" like this:
$a = true;
$b = true;
$c = false;
$isTrue = $a&$b | $b&$c | $c&$a;
print_r( $isTrue );
Let check by your self :D
So I just did some random test and understand the fundamentals of Precedence and the || and or operators but I'm having trouble understanding why $f changes:
$f = 0 || 1;
if ($f === 1){
echo "TRUE - $f";
}else{
echo "FALSE - $f";
}
$f = 0 or 1;
if ($f === 0){
echo "TRUE - $f";
}else{
echo "FALSE - $f";
}
Thanks for some insight.
What you are doing is the same as :
if (($f = 0) or 1){
// $f is being assigned the value 0, and the condition evaluates 0 or 1,
// 1 being equivalent to true, the condition is always true.
echo "TRUE - $f";
}else{
echo "FALSE - $f";
}
and
if ($f = (0 || 1)){ // which gives $f = true which returns true
echo "TRUE - $f";
}else{
echo "FALSE - $f";
}
if you want to check if $f is equal to a value or another you would do
if ($f === 0 or $f === 1)
Be aware that in php, by default an int 1 will be evaluated to bool true unless you do a strict comparison === or !==
It's normal to evaluate always to True. The reason is that OR means if that one of the values is True it will take this one.
Update to your new question:
The answer is that "||" has a greater precedence than "or"
// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;
// The constant false is assigned to $f and then true is ignored
// Acts like: (($f = false) or true)
$f = false or true;
You can learn more at the PHP manual website here which I found this example
the problem is here: "if ($f = 0 or 1){" :
"=" means you give the variable $f the value 0
You should use :
"==" : checks if the values are equal
"===" : checks if the left variable is identical to the right variable (value, type, etc.)
I want to do something like this:
if( $a = 'something' && $b = substr( $a, 2 ) )
{
//do something
}
I mean, on an if condition, evaluate two conditions, and the second one passing the first assigned $a as a parameter to the second condition function substr().
It is just an example, so I don't want answers to this functionality, just generic answers.
The above code throws 'Undefined' $a, since $a is not still assigned.
I could do the next:
if( $a = 'something')
{
if( $b = substr( $a, 2 ) )
//do something
}
}
but this will make my code bigger.
Is there any way to achieve something like the first example?
Edit:
I don't want to compare. Just assign and ensure that $a and $b are not null, false, ...
Your only problem is the wrong precedence of the && and = operators. This works just fine:
if (($a = 'something') && $b = substr($a, 2))
This way, $a is undefined:
if ($a = 'something' && $b = substr($a, 2))
But if you give the = operator priority:
if (($a = 'something') && $b = substr($a, 2))
It will be set.
Moreover, you can simply write:
if( $b = substr( $a = 'something', 2 ) )
This question intrigued me along with #moonwave99 answer, so I did some testing with his last answer.
if( $b = substr( $a = NULL, 2 ) ) { echo "PASS"; } else { echo "FAIL"; }
FAIL
if( $b = substr( $a = FALSE, 2 ) ) { echo "PASS"; } else { echo "FAIL"; }
FAIL
if( $b = substr( $a = 0, 2 ) ) { echo "PASS"; } else { echo "FAIL"; }
FAIL
if( $b = substr( $a = TRUE, 2 ) ) { echo "PASS"; } else { echo "FAIL"; }
FAIL
if( $b = substr( $a = 233, 2 ) ) { echo "PASS"; } else { echo "FAIL"; }
PASS
if( $b = substr( $a = "SOMETHING", 2 ) ) { echo "PASS"; } else { echo "FAIL"; }
PASS
The only way to get it to fail was to pass the Boolean TRUE. But if you are expecting string values, it should fail all Boolean values, zero and NULL and evaluate to true on ints, floats, and string values. (Haven't tested with array, but I suspect it would fail for any non-primitive types). Interesting question.
Use isset() for that.Also keep in mind use == or === for comparison operations since = is assignment operator
if( (isset($a) && $a == 'something') && (isset($b) && $b == substr( $a, 2 )) )
{
//do something
}
In my last project I had to specify a value, normally I use the following statement:
<?php
$true = 1;
$false = 0;
$hasAccess = $true ? 1 : 0;
print $hasAccess;
?>
but this works to:
<?php
$true = 1;
$false = 0;
$hasAccess = $true || $false;
print $hasAccess;
?>
Why?
Update: I know what a OR / || is and what I have to expect from it. But I haven't seen this possibility any time before.
Because 0 is automaticly casted to (bool)false, and anything else (bool)true.
So what you are basicly saying is:
$hasaccess = true OR false;
See also:
http://php.net/manual/en/language.types.boolean.php
http://php.net/manual/en/language.operators.logical.php
Because
$true ? 1 : 0;
evaluates to 1, since $true is true, and
$true || $false;
also evaluates to 1, for the same reason.
The OR will return true if either side of the expression true.
Since $true = 1 then the expression as a whole is true.
Basically you're saying "if $true is true, or $false is true then then $hasAccess is true"
An || which is an OR statement returns weather one of the statements evaluates to true.
Examples:
$bool = true || false;
// $bool = true
$bool = false || true;
// $bool = true
$bool = false || false;
// $bool = false
$bool = false || true || false;
// $bool = true
$bool = false || 1;
// $bool = true
$bool = false || 'test';
// $bool = true