How can I restructure `if` and `else` statements in PHP - php

I have two (and sometimes) three variables which determine if I should run a specific code. The problem is that any of them can be true or false and sometimes this leads to messy codes.
For three variables, there are 8 possible scenarios that I have to check. Like this:
if($var_a && $var_b && $var_c) {
// Do this (A)
} else if(!$var_a && $var_b && $var_c) {
// Do this (B)
} else if($var_a && !$var_b && $var_c) {
// Do this (C)
} else if(!$var_a && !$var_b && $var_C) {
// Do this (D)
}
... and so on.
Is there any way to use nesting and make this code less messy? It gets confusing at times to keep track of so many possibilities.
It might be easier to understand what I am saying with an example of two variables.
if($var_a && $var_b) {
// Do this (A)
} else if($var_a && !$var_b) {
// Do this (B)
} else if(!$var_a && $var_b) {
// Do this (C)
}
Is there any way to combine these conditions together so that I don't have to use so many && and if else conditions? This will make things less confusing for me when I have to deal with three (may be more) variables.

I guess you should try something like lookup map with bitwise map, in your case, it can be something like this:
$bitOne = $var_a ? 1 : 0;
$bitTwo = $var_b ? 2 : 0;
$bitThree = $var_c ? 4 : 0;
$resultKey = $bitOne | $bitTwo | $bitThree;
$map = [
7 => function() { return 'All are true'; },
3 => function() { return 'var_a and var_b are true'; },
6 => function() { return 'var_b and var_c are true'; },
// and so on
];
$result = $map[$resultKey];

If you extract the common variable (or an arbitrary choice in this case), you can produce a more layered approach, although the combinations will still mount up and it looks more code, it should be clearer...
if($var_a) {
if(!$var_b) {
// $var_a && !$var_b
}
else {
// $var_a && $var_b
}
}
else {
if($var_b) {
// !$var_a && $var_b
}
}

Related

Is this a good way of writing long conditions in PHP?

I have to evaluate a very long condition in PHP, so, to avoid errors and trying to write more readable code, I did the following:
//this returns 1 when true, and nothing when false, although expected TRUE or FALSE
$isNameValid=strlen($dataDecoded['nombre'])>=3;
$isDescriptionValid=(strlen($dataDecoded['descripcion'])>=10) && strlen($dataDecoded['descripcion'])<=300;
$isPriceValid=$dataDecoded['precio'] >0;
$isImageValid=(($dataDecoded['imagen'] != "") && ($dataDecoded['imagen'] != NULL) );
And now, I can make the following:
if($isNameValid==1 && $isDescriptionValid==1 && $isPriceValid==1 && $isImageValid==1)
{
echo "ok";
}
else{
echo "no";
}
It seems to work fine, but maybe is a weird way of doing things. I wanted to avoid the following, which I find more confusing and easy to make a mistake
if(strlen($dataDecoded['nombre'])>=3 && ... && ...)
Is there a better way to do that? Is wrong what I did? Thanks
I don't care for creating extra variables here; this makes code difficult to maintain and unreusable. I'd recommend breaking your validation logic into easy-to-read, maintainable, reusable functions:
function valid($data) {
return validName($data['nombre']) &&
validDescription($data['descripcion']) &&
validPrice($data['precio']) &&
validImage($data['imagen']);
}
function validName($name) {
return strlen($name) >= 3;
}
function validDescription($desc) {
return strlen($desc) >= 10 && strlen($desc) <= 300;
}
function validPrice($price) {
return $price > 0;
}
function validImage($image) {
return $image !== "" && $image != NULL;
}
$dataDecoded = [
"nombre" => "foo",
"descripcion" => "foo bar foo bar",
"precio" => 15,
"imagen" => "foo.png"
];
// now your main code is beautiful:
echo (valid($dataDecoded) ? "ok" : "no") . "\n";
Yes, that is acceptable. However, your variables there are all boolean, so you don't even need the ==1.
if($isNameValid && $isDescriptionValid && $isPriceValid && $isImageValid)
It really depends on how you want to handle it.
Is switch an option or a viable one?
Is ternary if prettier or handy?
From what I see, I'm guessing you have a validation purpose and a operating incoming depending on the validation. Why not create a function or a class that handles your input and validates? And in there, you can have all the dirty code you'd want. On your logical code, you'd just have to do (e.g of a class)
$someClass = new SomeClass();
$someClass->validate($fields);
if ($someClass->isValidated()) ...
This way, you'd actually follow some standards whereas the purpose of it would be to work as a validator for (all of? depends on your needs) your data
E.g of ternary ifs
$isNameValid = count($dataDecoded['nombre'])>=3 ? true : false;
$isDescriptionValid = count($dataDecoded['descripcion']) >= 10 && count($dataDecoded['descripcion']) <= 300 ? true : false;
$isPriceValid = count($dataDecoded['precio']) > 0 ? true : false;
$isImageValid = empty($dataDecoded['imagen']) === false ? true : false;
if ($isNameValid && $isDescriptionValid && $isPriceValid && $isImageValid) ...

Advice in design about Control Structure else if, switch o a better way?

I made the script to do what is expected, so it work ok but there must be a more elegant way to achieve the same result. I know that using switch will make it look nicer but not sure if the result will be the same as the 'default:' behavior:
This is the section of the script i want to refactor:
foreach ($free_slots as $val) { // here i am looping through some time slots
$slot_out = $free_slots[$x][1];
$slot_in = $free_slots[$x][0];
$slot_hours = $slot_out - $slot_in;
// tasks
if ($slot_out != '00:00:00') {
// Here i call a function that do a mysql query and
// return the user active tasks
$result = tasks($deadline,$user);
$row_task = mysql_fetch_array($result);
// HERE IS THE UGLY PART <<<<<----------------
// the array will return a list of tasks where this current
// users involved, in some cases it may show active tasks
// for other users as the same task may be divided between
// users, like i start the task and you continue it, so for
// the records, user 1 and 2 are involved in the same task.
// The elseif conditions are to extract the info related
// to the current $user so if no condition apply i need
// to change function to return only unnasigned tasks.
// so the i need the first section of the elseif with the
// same conditions of the second section, that is where i
// actually take actions, just to be able to change of
// change of function in case no condition apply and insert
// tasks that are unassigned.
if ($row_task['condition1'] == 1 && etc...) {
} else if ($row_task['condition2'] == 1 && etc...) {
} else if ($row_task['condition3'] == 1 && etc...) {
} else if ($row_task['condition4'] == 1 && etc...) {
} else {
// in case no condition found i change function
// and overwrite the variables
$result = tasks($deadline,'');
$row_task = mysql_fetch_array($result);
}
if ($row_task['condition1'] == 1 && etc...) {
// insert into database
} else if ($row_task['condition2'] == 1 && etc...) {
// insert into database
} else if ($row_task['condition3'] == 1 && etc...) {
// insert into database
} else if ($row_task['condition4'] == 1 && etc...) {
} else {
echo 'nothing to insert</br>';
}
}
}
Basically i run the else if block twice just to be able to change of function in case nothing is found in the first loop and be able to allocate records unassigned.
I haven't changed the functionality of your code, but this is definitely a lot cleaner.
The main problem was that your logic for your if/else statements was confused. When you're writing:
if($a == 1){ } else if($b == 1){ } else if($c == 1){ }else{ //do something }
You're saying If a is 1 do nothing, if b is 1 do nothing, if c is 1 do nothing, but if all of those did nothing, do something when you can just say if a is not 1 and b is not 1 and c is not 1, do something.
I wasn't too sure on your second if statements, but generally it's not good to have an if else with no body within it. However, if the "insert into database" comment does the same thing, you can merge the 3 if statements that do the same code.
I hope i've cleared a few things up for you.
Here's what I ended up with:
foreach ($free_slots as $val) { // here i am looping through some time slots
$slot_out = $free_slots[$x][1];
$slot_in = $free_slots[$x][0];
$slot_hours = $slot_out - $slot_in;
// tasks
if ($slot_out != '00:00:00') {
$result = tasks($deadline, $user);
$row_task = mysql_fetch_array($result);
if (!($row_task['condition1'] == 1 || $row_task['condition2'] == 1 || $row_task['condition3'] == 1 || $row_task['condition4'] == 1)) {
$result = tasks($deadline,'');
$row_task = mysql_fetch_array($result);
}
if ($row_task['condition1'] == 1 && etc...) {
// insert into database
} else if ($row_task['condition2'] == 1) {
// insert into database
} else if ($row_task['condition3'] == 1) {
// insert into database
} else if ($row_task['condition4'] == 1) {
} else {
echo 'nothing to insert</br>';
}
}
}

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 => ""
);

variable if() statements from a setting?

So let's say I have an option page that will set $threshold as '1', '2', '3', '4', or '5'
I've got a form that submits/redirects differently based on that threshold (right now the threshold is set to three only, not changeable, so one, two, and three go to PAGE ONE and do FUNCTION ONE, while four and five got to PAGE TWO and do FUNCTION TWO.
I want people to be able to set their own threshold.
currently I have:
if($foo == 'five' || $foo == 'four' || $foo == 'three'){
//DO ALL THIS CRAZY STUFF
} else {
//DO ALL THIS OTHER STUFF
}
what I WANT is basically a threshold wrapped around that:
if($threshold == '5'){
if($foo == 'five'){
//DO ALL THIS CRAZY STUFF
} else {
//DO ALL THIS OTHER STUFF
}
} else if ($threshold =='4'){
if($foo =='five' || $foo == 'four')
if($foo == 'five'){
//DO ALL THIS CRAZY STUFF
} else {
//DO ALL THIS OTHER STUFF
}
}
etc. for 3, 2, and 1 as well.
Is there an easy way to do that? Like should I set the if/or statements as variables? like:
if($threshold == '5'){ $var = "$foo =='five'" }
else if($threshold == '4'){ $var = "$foo =='five' || $foo == 'four'" }
then do
if($var){
//DO ALL THIS CRAZY STUFF
} else {
//DO ALL THIS OTHER STUFF
}
??
I'm not quite sure the 'best approach' to this :/
I'm not really sure if, for different $threshold numbers and $foo combinations, you have different functions for each of them, or if you just want to know if $foo is located within the specified $threshold. I guess the latter is your goal:
// the map
$thresholds = array(
5 => array('five'),
4 => array('five','four'),
// etc
);
// dummy values
$threshold = 5;
$foo = "four";
// check values
if(array_key_exists($threshold,$thresholds)) {
if(in_array($foo, $thresholds[$threshold])) {
//DO ALL THIS CRAZY STUFF
}
else {
//DO ALL THIS OTHER STUFF
}
}
If you have to make complex decisions, based on multiple vars, a good strategie is to build a map.
A map is a multi dimension array and has a function name or a closure as a value. What you do is lookup what function to call based on the keys of the array.

Categories