PHP - IF doing all the time only first condition, why? [duplicate] - php

This question already has answers here:
The 3 different equals
(5 answers)
Closed 5 years ago.
why the IF(the lastest one with else if and else) is doing all the time only first condition and only the first part ($filtry_1value[$key] = 'min_cena'), even if the condition shouldnt be true. I have another solution (less dynamic), if I will not fix this one, but I would like to know, why it is not working... I think it will be a trivial thing, but I cannot see it.
PS: I am working with laravel.
$filtry_1value = ['stat', 'lokalita', 'patro', 'min_cena', 'max_cena', 'min_uzitna_plocha', 'max_uzitna_plocha'];
foreach ($filtry_1value as $key => $filtr_1value) {
$filtr_1value = \Request::has($filtr_1value) ? \Request::get($filtr_1value) : null;
if(!empty($filtr_1value)){
if ($filtry_1value[$key] = 'min_cena' OR $filtry_1value[$key] = 'min_uzitna_plocha') {
$query->where(substr($filtry_1value[$key], 4),'>=',$filtr_1value);
}
elseif ($filtry_1value[$key] = 'max_cena' OR $filtry_1value[$key] = 'max_uzitna_plocha') {
$query->where(substr($filtry_1value[$key], 4),'<=',$filtr_1value);
}
else {
$query->where($filtry_1value[$key],'=', $filtr_1value);
}
}
}

may be-
foreach ($filtry_1value as $key => $filtr_1value) {
$filtr_1value = \Request::has($filtr_1value) ? \Request::get($filtr_1value) : null;
if(!empty($filtr_1value)){
if ($filtry_1value[$key] == 'min_cena' OR $filtry_1value[$key] == 'min_uzitna_plocha') {
$query->where(substr($filtry_1value[$key], 4),'>=',$filtr_1value);
}
elseif ($filtry_1value[$key] == 'max_cena' OR $filtry_1value[$key] == 'max_uzitna_plocha') {
$query->where(substr($filtry_1value[$key], 4),'<=',$filtr_1value);
}
else {
$query->where($filtry_1value[$key],'=', $filtr_1value);
}
}
}

You need to use the double equal sign for comparisons. == not a single =
Your if's should look like:-
if ($filtry_1value[$key] == 'min_cena' OR $filtry_1value[$key] == 'min_uzitna_plocha') {
// ...
} elseif ($filtry_1value[$key] == 'max_cena' OR $filtry_1value[$key] == 'max_uzitna_plocha') {
// ...
}

Related

Why does this && not trigger as false? [duplicate]

This question already has answers here:
whats the difference in parentheses in IF statements?
(9 answers)
Closed 2 years ago.
I have this simple if statement but I do not get the results I expect. If all three vars match then I get not supported as expected. However I expect that as soon as I change one of the vars to a value that is not in the if statement, e.g. $Main = "SomethingElse", for the if statement to not match and therefor echo supported. However, supported is only returned if all three vars do not match the if statement.
Why does this happen?
$Main = "Main_Other";
$Backup = "Back_None";
$online = "no";
if ($online == "no" && $Main == "Main_Other" && $Backup == "Back_Other" || $Backup == "Back_None") {
echo "not support";
} else {
echo "supported";
}
In your example the if statement will always return true if the value of $backup is set to Back_None.
Try using below code. Here it will check $backup value first using || operator and then it will check the result with && operator
$Main = "Main_Other";
$Backup = "Back_None";
$online = "no";
if ($online == "no" && $Main == "Main_Other" && ($Backup == "Back_Other" || $Backup == "Back_None")) {
echo "not support";
} else {
echo "supported";
}

if condition with foreach loop for array in php

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";
}
}

PHP - else, 'escape' nesting and skip to elseif

I wasn't too sure how to title this question - Here's a snippet of what I'm doing:
<?php
if ($result_rows >= 1 && $membership = 'active') {
if ($when_next_allowed > $today_date) {
$output = 'You cannot renew your membership for another <b>' . $days_left . 'days</b>.';
}
/*
What if the membership is set to active, but it's been over a year since they
activated it? We don't have any server-side functions for determining such
at the time.
*/
else {
/* do database stuff to change the database entry to inactive */
/* skip to elseif below */
}
}
elseif (2 == 2) {
/* create new database entry for user's membership */
}
?>
If the first nested argument is false, it should move onto else which should continue from there and 'escape' the 'parent' if and move onto elseif. Other wise, if the first nested argument is true, then it should stay put.
Is that even a possible occurrence? The only thing I could think of was to add multiple continue; commands. That, of course, threw an error.
One other idea I had was setting a variable to equal continue; within the else, then set that right before the end of the parent if:
if (1 == 1) {
...
else {
$escape = 'continue;';
}
/* $escape here */
}
But I've never heard of, nor do I know of any method of using variables in a 'raw' form like that. Of course I've done research on it, though I've yet to find out how. I'm not sure if that's common knowledge or anything - But I've never heard of, or considered such a thing until now.
Solution? This is something I always thought about, though I never knew I'd have to use it.
Cleanest I could come up with:
$run = false;
if (1 == 1) {
$run = true;
if (1 == 2) {
/* Do something */
} else {
$run = false;
/* Do something else */
}
}
if (!$run && 2 == 2) {
}
Alternatively, you could use a goto between [Do something else] and the 2nd if block, but it'll be messy either way.
if (1 == 1) {
if (1 == 2) {
/* Do something */
} else {
/* Do something else */
goto 1
}
} else if (!$run && 2 == 2) {
1:
}
If I understand the problem correctly, then you could just do something like this:
if (1==1 && 1==2) {
/* ... */
}
elseif (2==2) {
$success = 'Success';
}
Obviously, I don't need to point out that 1==1 && 1==2 is completely illogical and is just used as an example of two boolean statements.
Update based on update to question:
Unless there are additional steps that you are omitting, this replicates your logic. Hard to know if this really solves your problem, because I don't know what 2==2 represents, or what other steps you might need to perform based on what other conditions.
if (($result_rows >= 1 && $membership == 'active') &&
($when_next_allowed > $today_date)) {
$output = 'You cannot renew your membership for another <b>' . $days_left . 'days</b>.';
}
elseif (2 == 2) {
/* create new database entry for user's membership */
}
This should do what you want to do.
If you have a variable to false and switch it to true if you go into the else you want, you just have to test the value of this variable right after to go into elseif you wanted to go in.
<?php
$test = false;
if (1 == 1) {
if (1 == 2) {
/* ... */
}
else {
/* Skip to elseif below */
$test = true;
}
}
if ($test == true) {
$success = 'Success';
}
echo $success;
?>
Not an easy question as it's really hard to understand what you're trying to achieve but I think this is the solution you're looking for.
<?php
$success = False;
if (1 == 1) {
if (1 == 2) {
/* ... */
} else {
$success = True;
/* True case code can go here */
}
}
echo $success;
?>
pseudo code is your friend.
Alternatively;
<?php
$success = False;
if (1 == 1) {
if (1 == 2) {
/* ... */
} else {
$success = True;
}
}
if $success == True {
/* ... */
}
echo $success;
?>
<?php
$continue = false;
if (1 == 1) {
if (1 == 2) {
/* ... */
}
else {
$continue = true;
}
}
if ($continue==true) {
$success = 'Success';
}
echo $success;
?>

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";
}

Nesting if else statements in PHP to validate a URL

I'm currently writing up a function in order to validate a URL by exploding it into different parts and matching those parts with strings I've defined. This is the function I'm using so far:
function validTnet($tnet_url) {
$tnet_2 = "defined2";
$tnet_3 = "defined3";
$tnet_5 = "defined5";
$tnet_7 = "";
if($exp_url[2] == $tnet_2) {
#show true, proceed to next validation
if($exp_url[3] == $tnet_3) {
#true, and next
if($exp_url[5] == $tnet_5) {
#true, and last
if($exp_url[7] == $tnet_7) {
#true, valid
}
}
}
} else {
echo "failed on tnet_2";
}
}
For some reason I'm unable to think of the way to code (or search for the proper term) of how to break out of the if statements that are nested.
What I would like to do check each part of the URL, starting with $tnet_2, and if it fails one of the checks ($tnet_2, $tnet_3, $tnet_5 or $tnet_7), output that it fails, and break out of the if statement. Is there an easy way to accomplish this using some of the code I have already?
Combine all the if conditions
if(
$exp_url[2] == $tnet_2 &&
$exp_url[3] == $tnet_3 &&
$exp_url[5] == $tnet_5 &&
$exp_url[7] == $tnet_7
) {
//true, valid
} else {
echo "failed on tnet_2";
}
$is_valid = true;
foreach (array(2, 3, 5, 7) as $i) {
if ($exp_url[$i] !== ${'tnet_'.$i}) {
$is_valid = false;
break;
}
}
You could do $tnet[$i] if you define those values in an array:
$tnet = array(
2 => "defined2",
3 => "defined3",
5 => "defined5",
7 => ""
);

Categories