Mapping Woocommerce order statuses using IF statements - php

In Woocommerce, I am trying to map orders statuses with the following code:
function my_map_status ($status) {
if ($status == "wc-processing") {
return "WAA";
} else {
return $status;
}
if ($status == "wc-cancelled") {
return "WAC";
} else {
return $status;
}
}
But only the first one works.
How can I make it work for both?

The first IF ELSE statement is taking every possibility. Instead use an IF ELSEIF ELSE structure:
function my_map_status ($status) {
if ($status == "wc-processing") {
return "WAA";
} elseif ($status == "wc-cancelled") {
return "WAC";
} else {
return $status;
}
}
It should better work.

The reason it's not getting beyond the first if is that it has an else that just returns - so, if you think it through logically you will see that if $status is not wc-processing then return (and quit function) - in other words, it never gets beyond the first if.
Instead, you might like to consider using switch/case, which makes for much easier reading than multiple if/elseifs, like this:
switch ( $status ) {
case "wc-processing":
return "WAA";
break;
case "wc-cancelled":
return "WAC";
break;
default:
return $status;
}
(in case you're wondering about the break - although not strictly necessary in this case (as the function will be exited with the return) it is good practice IMHO to always remember to use it every time you write a switch structure. More info on the page below.)
Further reading: http://php.net/manual/en/control-structures.switch.php

Related

Where/When we should use return false in php [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I did a lot of search but couldn't find any clear guide. Please one of you experts answer my question.
Where/when we should use "return false" in an array or an if statement.
for example :
if(file_exists($p)) {
// do something
} else {
echo $error;
return FALSE;
}
whole code:
class Base {
function __construct() {
$url = $_GET['url'];
$url = explode('/',$url);
$p = $url[0].'.php';
if(file_exists($p)) {
require($p);
} else {
require('error.php');
$error = new error();
$error->Not_Exist();
return FALSE;
}
}
Please someone explain me the reasons for use of return false.
Firstly, it only makes sense to return a value if it is potentially going to be used. You can return whatever you want, even if it is not going to be used, but what would be the point?
This makes sense:
function isOfAge($age) {
if ($age >= 18) {
return true;
}
return false;
// Shorter:
// return $age >= 18;
}
This does not make much sense:
function outputName($name) {
echo "Your name is {$name}!";
return true;
}
Secondly, boolean values should only be returned if the result of a function is boolean in nature, such as functions that:
Evaluate or compare values (e.g. isOfAge($age), containsCharacter($str, $char), canBeExecuted($pathToExe), validDate($date), sameValues($a, $b), etc.)
Execute or run something and report back the result (e.g. executeSQL($sql), generateImage($data), runBackgroundProcess($str), etc.)
You can also return a boolean value only if a function fails (or succeeds), such as:
function createName($first, $second) {
if (strlen($first) === 0 || strlen($second) === 0) {
return false;
}
return "{$first} {$second}";
}
And then you can use the return value to check if it worked, and if it did then you can be sure that it contains a string:
$name = createName("Sverri");
if ($name === false) {
die("Invalid first or second name!");
} else {
echo "Hello $name!";
}
That function could also be written using exceptions. Exceptions allow you to stop the script, throw an error, catch that error, and then continue the script:
function createName($first, $second) {
if (strlen($first) === 0) {
throw new \Exception("Invalid first name");
}
if (strlen($second) === 0) {
throw new \Exception("Invalid second name");
}
return "{$first} {$second}";
}
try {
echo createName("Sverri");
} catch (\Exception $e) {
die($e->getMessage());
}
A good rule of thumb is to ask yourself if it makes sense to return a boolean value, and if the returned value is going to be used.
In the code in your question it would not make sense to return any value. You cannot return anything in a constructor anyway, so returning something does not make sense.
If you want to terminate a function without a return value you can just do so:
function uselessFunction() {
return;
}
It will actually return a value, null, but when you just want to terminate a function without returning any particular value then that is how you would do it.
I personally normally use them in functions to tell me if something is happening.
<?php
function isUsernameAvailable($username)
{
// Some db functions.
if ($db->rowCount() == 1) return false;
return true;
}
?>
So if the provided username does not exist in the database then it will return true otherwise it will return false.
Usage,
if (isUsernameAvailable("test") == false) {
// Username does not exist.
} else {
// Username exists.
}

if and else both are true in my php codes

i wonder that both if and it's else are true.
i got $apple_id_num from the input select form and it is a number but in string type like "7" and it is how many ids that user wants.so i convert it to integer
now i want to check if it is not more that what i have available in my database.
but statements under conditions ($num_rows<$id_num) and if ($num_rows>=$id_num) both are running.
what i'm doin wrong?
here is my code:
function getAppleID($apple_id_num)
{
$sqli=new mysqlii();
$apple_ids=$sqli->SelectFromDB($apple_id_num);
$num_rows=$sqli->num_rows;
$id_num=(int)$apple_id_num;
if ($num_rows>=$id_num){
$this->printAppleID($apple_ids,$num_rows);
//$sqli->updateRows();
echo"else if running";
return $apple_id_num;
} else if ($num_rows<$id_num)
echo "if statement was rungning";
}
Try this code. always write intended code. Sometimes you may miss a } :P
Use elseif in place of else if.
function getAppleID($apple_id_num)
{
$sqli=new mysqlii();
$apple_ids=$sqli->SelectFromDB($apple_id_num);
$num_rows=$sqli->num_rows;
$id_num=(int)$apple_id_num;
if ($num_rows>=$id_num) {
$this->printAppleID($apple_ids,$num_rows);
//$sqli->updateRows();
echo"else if running";
return $apple_id_num;
} elseif ($num_rows<$id_num) {
echo "if statement was rungning";
}
}

Getting around duplicating code in complex if/else statements

I come across this problem all the time: you have a series of if/else statements, where the intended result can come from two completely different branches, and you end up duplicating the code across both. Here's an example:
if (condition1) {
return error
} else {
if (condition2) {
return intendedResult
} else {
if (condition3) {
return error
} else {
return intendedResult
}
}
}
I have this problem in a PHP script at the moment, where the intended result is approximately 200 lines of PHP queries, HTML and additional if/else statements. Is this the prime example of when you should use a function? And return all that code in a concatenated string?
EDIT:
Thanks for all your replies. I can see that my logic would need tidying up. If I gave you a real-world example, could you help me restructure my logic? I think it's a little more complicated than my pseudo-code.
I pull two dates, $lift_deadline and $show_guide_close from a database, and depending on today's date's relation to those, do the following:
if ($lift_deadline > $today) {
echo "No access until " . $lift_deadline;
} else {
if ($lift_deadline !== "0000-00-00") {
if ($today > $show_guide_close) {
$use_date = $show_guide_close;
} else {
$use_date = $lift_deadline;
}
echo "HTML Table"; // Intended result goes here, using $use_date
} else {
if ($show_guide_close > $today) {
echo "No access until " . $show_guide_close;
} else {
$use_date = $show_guide_close;
echo "HTML Table"; // Intended result also goes here
}
}
}
Well part of the solution is certainly making intendedResult code into a separate method, but just reoganizing the conditions can help:
if ($condition1) {
return 'error';
}
if (!$condition2 && $condition3) {
return 'error';
}
return $this->intendedResult();
This could be further simplified to:
return ($condition1 || $condition3) ? 'error' : $this->intendedResult();
But that might not be as readable, and doesnt really illustrate my point, which is as Tom mentions, to flatten your control structure
Yes, functions are one way to simplify code and make it easier to read. It might be also worth looking into classes and exceptions.
In simple instances I use a switch statement for stuff like this
switch(true)
{
case (condition1):
break;
case (condition2):
break;
default:
}

Nested if, not exiting - create a function to call functions

I have the following code to validate form data. I have created functions to validate various groups, and then have an if isset statement to check if these functions return true. I have tried many different ways to get this to work.
The problem I am having is this. I want the if isset to end if returning FALSE; but it doesn't, it keeps going and pops up the next alert (in my code I have many functions). How can I get it to exit after the first return FALSE? Do I need to make the isset into a function? So it can exit on return FALSE. thanks
I am having trouble writing a function to call functions in php.
function namecheck ($fname, $lname)
{
$regexp ="/^[A-Za-z]+$/";
//filter through names
if (preg_match($regexp,$fname,$lname))
{
return TRUE;
}
else
{
echo'<script type="text/javascript">alert("Enter your names.")</script>';
return FALSE;
}
}
function emailcheck ($email1, $email2)
{
$regexp="/^[a-zA-A-Z0-9_.]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9.-]+$/";
//validate email address
if (preg_match($regexp,$email1,$email2))
{
return TRUE;
}
else
{
echo '<script type="text/javascript">alert ("Enter a valid email address.")</script>';
return FALSE;
}
}
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$namecheck=namecheck($fname,$lname);
$email1=$_POST['email1'];
$email2=$_POST['email2'];
$emailcheck=emailcheck($email1,$email2);
if (isset($_POST['submit']))
{
if ($namecheck !==TRUE)
{
return FALSE;
}
elseif ($emailcheck!==TRUE)
{
return FALSE;
} //and so on..
else
{
return TRUE;
}
}
A general structure for your functions you could follow is something like this:
function validateName($name) {
// Do Validation. Return true or false.
}
function validateEmail($email) {
// Do Validation. Return true or false.
}
function isFormValid()
{
// Name Validation
if( ! validateName( $_POST['name'] ) )
return false;
// Email Validation
if( ! validateEmail( $_POST['email'] ) )
return false;
// Form is valid if it reached this far.
return true;
}
// In your regular code on Form Submit
if( isset($_POST['submit']) )
{
if( isFormValid() ) {
// Save Form Data to DB
} else {
// Show Some Errors
}
}
That general structure should work fine for you. It could be made a LOT better but, for the sake of learning, this is sufficient.
If you want the script to, as you put, "exit" then you need to use exit(); Generally this is bad as the script will completely stop executing. Maybe you can look into using "break;" to get you out of a loop and stop executing functions within that loop. Another problem is that you are echoing out HTML code in your function which gets executed on assignment and so you will always get an alert generated when it evaluates to FALSE.
edit:
within your if(isset()) block. Inside here you can do{}while(false); which is a loop and will let you break out of it at anytime and prevent further execution of code within that loop.
If a function isn't returning false, then it never reached a return FALSE; statement. It's as simple as that. So let's examine the relevant code:
if (isset($_POST['submit']))
{
if ($namecheck !==TRUE)
{
return FALSE;
}
elseif ($emailcheck !== TRUE)
{
return FALSE;
} //and so on..
else
{
return TRUE;
}
}
So, if $_POST['submit'] is set and is not null, the if block will be reached. Then, if $namecheck is not true OR $emailcheck is not true, the function will return FALSE. You can simplify the above code to just:
if (isset($_POST['submit']))
{
return !(!$namecheck || !$emailcheck);
}
However, it doesn't look like this code is inside a function, so the return statement will do nothing. You have to put it in a function if you want it to work like a function.
Beyond that, I can't help you. I don't know what you want to do with this code. You seem to know how to use and call functions, so I'm not sure what the problem is. If you want to return from a function, put code in a function and call return. Right now your code is not in a function, so return won't do anything.

if statement running regardless of true false

I have tested each method individually with default values and it all seems to work. There is something going on when they are all mixed together.
Here is the code and i'll do my best to write it in an easy to follow way:
Starting with the controller:
if ($active['newcliq'])
{
$newcliqid = $this->create_m->create_keyword($cliq, $cliqid);
if (!$newcliqid) {
echo json_encode(array('success' => false));
} else {
$this->logic_m->change_active($newcliqid, $cliq);
}
}
$active['newcliq'] is true or false and pulled from userdata('active')
Of course, the next thing it runs is create_keyword($cliq, $cliqid) seen below:
$this->db->insert('cliq', $insert);
$newcliqid = $this->db->insert_id();
if ($newcliqid) {
return $newcliqid;
} else {
return false;
}
Again, I have checked it all manually, and I know that $newcliqid is returning the correct insert_id and the overall function is returning the correct value.
So $newcliqid is returned to the controller and goes runs logic_m->change_active seen below:
if (!$this->logic_m->cliqidcheck($cliqid)){
$cliqid = 6;
}
The above line is what is giving me problems. No matter what value, $cliqid is ALWAYS set to 6. Whether cliqidcheck returns true or false.
Here is cliqidcheck($cliqid)
public function cliqidcheck($cliqid)
{
if ((ctype_digit($cliqid)) AND ($this->checkcliqidexist($cliqid)))
{
return true;
} else {
return false;
}
}
I have tested cliqidcheck with manually entered values and it always returns the correct value. In addition, i've flat out removed the cliqidcheck from the change_active model and it works perfectly.
I also echo'ed the variable $newcliqid in the controller and found the correct value.
I am hoping this is just a simple problem that I'm overlooking. Thanks for the help! Please let me know if more info is required.
Instead of verbal explanations, wouldn't be it better to post either the debugging code
var_dump($cliqid);
$tmp = $this->logic_m->cliqidcheck($cliqid);
if (!$tmp) {
$cliqid = 6;
}
var_dump($tmp, $cliqid);
die;
and it's output.
Even without posting it here it will convince you that if statement actually never "running regardless of true false"
Setting full error reporting also helps (with finding typos and such)
ini_set('display_errors',1);
error_reporting(E_ALL);
Also a note on excessive code. This statement
if (condition)
{
return true;
} else {
return false;
}
can (and should, in my opinion) be shortened to
return (condition);
Same goes for insert id. Why not to make it just
return $this->db->insert_id();
without all that windy
if ($newcliqid) {
return $newcliqid;
} else {
return false;
}
which is actually a mere tautology

Categories