Proper way of handling multiple cases - php

I have a method that can return 3 different cases
public function check_verification_status($user_id) {
global $db;
$sql = "SELECT * FROM `users`
WHERE `id` = ".clean($user_id)."
AND `type_id` = 1";
$result = #mysql_query($sql,$db); check_sql(mysql_error(), $sql, 0);
$list = mysql_fetch_array($result);
if ($list['verification_key'] == '' && !$list['verified']) {
//No key or verified
return 0;
} elseif ($list['verification_key'] != '' && !$list['verified']) {
//key exists but not verified = email sent
return 2;
} elseif ($list['verification_key'] != '' && $list['verified']) {
//verified
return 1;
}
}
A form / message is output depending on the return value from this
I would have used bool for return values when comparing 2 cases, what is the proper way of handling more than 2 cases and what would the ideal return value be.
The way i call this:
$v_status = $ver->check_verification_status($user_id);
if ($v_status === 0) {
//do something
} elseif ($v_status === 1) {
//do something else
} elseif ($v_status === 2) {
//do something totally different
}
I want to learn the right way of handling such cases as I run into them often.
note: I know I need to upgrage to mysqli or PDO, its coming soon

What you have is fine, but you can also use a switch statement:
$v_status = $ver->check_verification_status($user_id);
switch ($v_status) {
case 0: {
//do something
break;
}
case 1: {
//do something else
break;
}
case 2: {
//do something totally different
break;
}
}

Related

How i can use if/else/elseif statment in my case - PHP

How i can use if/else/elseif... in my case,
Because when i try those statment,
It says: syntax error, unexpected 'if' (T_IF)
I need to repeat elseif more than 1x time
$row = array();
$row[] = if($aRow['status'] == "deleted"){'code..'};
This might be what you are after. You would loop over each record in your result array you get from fetchAll(), put your if/elseif block here, then I'm assuming your doing some sort of processing and saving the value to $row array?
$row = array();
$result = $sth->fetchAll();
foreach($result as $aRow){
if($aRow['status'] == "deleted"){
//do something
$row[] = //whatever
}
elseif($aRow['status'] == "something else"){
//do something else;
$row[] = //whatever else
}
}
You have 2 ways for implementing this by PHP:
The 1st way
you can use if/else/elseif:
if ($status_var=="deleted")
{
//code .....
}
elseif ($status_var=="inserted")
{
//code .....
}
elseif ($status_var=="edited")
{
//code .....
}
esle
{
//code .....
}
The 2nd way
You can use switch/case structure:
switch ($status_var)
{
case "deleted":
//code .....
break;
case "inserted":
//code .....
break;
case "edited":
//code .....
break;
default:
//code .....
}
You can use ternary operator to assign the result:
$row = array();
$row[] = $aRow['status'] == "deleted" ? 'code..' : null;
When you need to do more things depending on status, best way would be to introduce a function for that:
function process($aRow) {
if ($aRow['status'] == "deleted") {
// do something when `deleted`
return 1;
} elseif ($aRow['status'] == "new") {
// do something when `new`
return 2;
} elseif ($aRow['status'] == "updated") {
// do something when `updated`
return 3;
} else {
// do something else
return 4;
}
}
$row = array();
$row[] = process($aRow);

Check if two vars are set?

Depending on whether 2 vars are set ($skip and $take) I want to do different things. I have a large if else statement, is there a more efficient way to write this?
if (isset($skip) && !isset($take)) {
//skip only
} elseif (!isset($skip) && isset($take)) {
//take only
} elseif (isset($skip) && isset($take)) {
//skip and take
} else {
//default
}
Edit
It should also be noted that this is to sit in a method where the vars will be set to null if not specified:
getAll($skip = null, $take = null)
You can simplify the logic a bit:
if (isset($skip) && isset($take)) {
// skip and take
} elseif (isset($skip)) {
// only skip
} elseif (isset($take)) {
// only take
} else {
// default
}
Since the OP clarified in a comment that this is inside a method, and both $skip and $take are arguments with default values, one might favor === over isset. Furthermore, you can re-arrange the logic a bit:
function getAll($skip = null, $take = null) {
if ($skip !== null && $take !== null) {
// both
} elseif ($skip !== null) {
// skip only
} elseif ($take !== null) {
// take only
} else {
// none
}
}
The === operator enforces an equality check with type safety.
The way default values for arguments work, the arguments are always guaranteed to be null if you don't pass them, so the equality check is a good way to check them here.
if you dont like if else
$switch = (int)isset($skip) + (int)isset($take)*2;
switch($switch){
case 0:
//default
break;
case 1:
//only skip
break;
case 2:
//only take
break;
case 3:
//skip and take
break;
}

How to execute both if and else blocks based on a condition into if-statement block?

I have a script like this:
if(isset($_SESSION["LoginValidation"]) && $_SESSION["LoginValidation"] == 1){
$something = $db->prepare('SELECT cookie FROM users WHERE id = ?');
$something->execute(array($_SESSION["Id"]));
$num_row = $something->fetch();
$_SESSION["cookie"] = $num_row['cookie'];
if ( $_SESSION["cookie"] != $_COOKIE['login']) ){
// jump to following else statement (outer else statement)
}
} else {
/* here - this block should be execute when
- That inner if-statement is true
OR
- That outer if-statement is false
*/
}
As you see, I need to execute if-statement and if inner if-statement is true then execute else-statement. How can I do that?
I think that is a algorithm problem and not php. Anyway, there are several ways to do. For example:
$innerCondition = false;
$outerCondition = false;
if(isset($_SESSION["LoginValidation"]) && $_SESSION["LoginValidation"] == 1) {
$outerCondition = true;
// ...
if ($_SESSION["cookie"] != $_COOKIE['login']) {
$innerCondition = true;
// ...
}
}
if ($innerCondition || !$outerCondition) {
// ...
}
Try something like this:
$doElse = true;
if(isset($_SESSION["LoginValidation"]) && $_SESSION["LoginValidation"] == 1){
$doElse = false;
$something = $db->prepare('SELECT cookie FROM users WHERE id = ?');
$something->execute(array($_SESSION["Id"]));
$num_row = $something->fetch();
$_SESSION["cookie"] = $num_row['cookie'];
if ( $_SESSION["cookie"] != $_COOKIE['login']) ){
$doElse = true;
}
else {
//rest of the logic
}
}
if ($doElse) {
// here - this block should be execute when inner if-statement is true
}

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

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;
?>

Categories