Currently, the only way I can think of to reasonably check for this without bloated logic:
if ( $value > 0 ) {
// Okay
} else {
// Not Okay
}
Is there a better way?
The logical negation of "greater than 0" is "equal or smaller than 0".
if ($value <= 0) { ... }
It is a normal way to resolve problem. Also you can use this:
$value > 0 ? echo "Okay"; : echo "Not Okay";
Couple of ways you can go about this.
if (!($value > 0)) {
//If value not greater than 0
}
if ($value <= 0) {
//If value equal to or less than 0
}
Or if it is a simple assignment / return you can go and use short-if.
//Assign to variable
$variable = $value > 0 ? 'greater' : 'equal to or less';
//Return from function
return $value > 0 ? 'greater' : 'equal to or less';
Related
Inside a JSON file I have multiple keys with the name type and their values are numeric. What I'm trying to do is to check if the exact number exists. The problem is that if have two values with the same digit it shows me both TRUE. Eg 41 & 1.
What I tried so far
$regex = '/^1$/';
foreach ($value['events'] as $event) {
if ($event['type'] == $regex) {
echo 'Exist';
}
}
Thank you
You can use array_column() and in_array()
if (in_array(1, array_column($value['events'], 'type'))) {
echo "Exist";
}
I was typing the same as Barmar's answer but this is another alternative. Just filter out the ones that don't equal your number:
if(array_filter($value['events'], function($v) { return $v['type'] == 1; })) {
echo "Exist";
}
This would be a better approach if you needed to test more than one condition such as:
return ($v['type'] == 1 || $v['type'] == 2);
//or
return ($v['type'] == 1 && $v['other'] == 'X');
I have $first and $second. They can have value 0 or 1.
if ( $first AND $second ) {
// True
} else {
// False
}
My mind (and Google search) tells me, that the result is true only when $first == 1 and $second == 0 or vice versa. But the result is true when both of this variables are 1.
I don't understand how does it works.
Your Google searches have failed you. PHP's type juggling means that a 1 is equivalent to TRUE and 0 is equivalent to FALSE. (See also type comparisons). So if both values are 1 then that if statement evaluates to TRUE. If one or both values are 0, it evaluates to FALSE.
<?php
$one = 1;
$zero = 0;
if ($one && $one) {
echo "true\n";
}
else {
echo "false\n";
}
if ($zero && $zero) {
echo "true\n";
}
else {
echo "false\n";
}
if ($one && $zero) {
echo "true\n";
}
else {
echo "false\n";
}
if ($zero && $one) {
echo "true\n";
}
else {
echo "false\n";
}
Program Output
true
false
false
false
Demo
In PHP all values are either "truthy" or "falsy" in expressions.
If a value contains something then it can be said to be truthy. So, values such as 1, "one", [1,2,3] or true all "contain" something and will be interpreted as truthy.
Values that are zeroed or in some way empty are falsy. E.g. 0, "", [] and false.
There is a table of how values are interpreted in the PHP documentation.
You can also just experiment, and output it to your website:
var_dump(1 and 0);
i got into some trouble by using OR if one condition is true and the other false.
in my constillation right now it is always only the second condition token.
if($num_rows === '0' OR $_GET['id'] !== $_SESSION['UserID'])
{ echo "show me something"; }
else
{ show nothing; }
i get only always 'show nothing'.
Note that === is strict comparison. I think the following:
$num_rows === '0'
should rather be:
$num_rows == 0
$num_rows is presumably an integer and not a string (a piece of text).
Related: PHP == vs === on Stack Overflow
Watch out with the second comparison, too:
$_GET['id'] !== $_SESSION['UserID']
Here, it's probably better to use != in favor of !== as well. $_GET is generally read as string, so even something like ?id=5 will return as string "5" and not as integer 5
Here's a quick test to illustrate:
if (isset($_GET['id'])) {
echo '<h2>Comparison with == 5</h2>';
var_dump( ($_GET['id'] == 5) );
echo '<h2>Comparison with == "5"</h2>';
var_dump( ($_GET['id'] == "5") );
echo '<h2>Comparison with === 5</h2>';
var_dump( ($_GET['id'] === 5) );
echo '<h2>Comparison with === "5"</h2>';
var_dump( ($_GET['id'] === "5") );
}
else {
echo 'Please set an ?id to test';
}
This will output (notice the third item is false) the following with ?id=5:
Comparison with == 5
boolean true
Comparison with == "5"
boolean true
Comparison with === 5
boolean false
Comparison with === "5"
boolean true
Probably because you use absolute equality with a string.Mysli_num_rows returns an int.
http://php.net/manual/en/language.operators.comparison.php
Equal and of the same type
You dont need to use === as it is a strict comparison and $num_rows is probably an int Try this:-
if($num_rows == 0 OR $_GET['id'] != $_SESSION['UserID'])
$_GET['id'] will provide you a string. You may chech the manual for details
To be really correct, need something like this:
if ($num_rows === FALSE) {
echo 'db resource/link gone';
}
elseif ($num_rows === 0 || intval($_GET['id']) !== intval($_SESSION['UserID'])) {
echo 'no db result or id mismatch';
}
elseif (intval($num_rows) > 0 && intval($_GET['id']) === intval($_SESSION['UserID'])) {
echo 'everything good';
}
else {
echo 'something unhandled went wrong';
}
thanks for all the answers. i got it to work. i change the order and the opreator to what you've suggested.
i made it like this:
if($num_rows > 0 OR $_GET['id'] == $_SESSION['UserID']) { echo "show nothing"; }
else { show me some stuff }
so thanks again for all the help. :)
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";
}
if(0 == ('Pictures'))
{
echo 'true';
}
why it's giving me 'true' ?
Your string will be evaluated as an Integer, so becomes 0, use this : 0 === 'Pictures' that verifies identity (same value and same type)
Check PHP type comparison tables to understand how comparison operators behave in PHP.
In your case, 'Pictures' becomes "0" and therefore 0 = 0.
Let's check following example:
echo (int)'Pictures'; // 0 => 'Picture' as int
echo 0 == 'Pictures'; // 1 => true, 0 = 0
Use:
if (0 === 'Pictures')
{
echo 'true';
}
The === is strict type operator, it not only checks the value but the type as well.
Quick Test:
if(0 == 'Pictures')
{
echo 'true';
}
else
{
echo 'false';
}
outputs true but:
if(0 === 'Pictures')
{
echo 'true';
}
else
{
echo 'false';
}
outputs false