0

I have an array which will have 3 cases like this:

First:

array: [
  "QtyIn" => "0"
  "QtyOut" => "0"
]

Second:

array: [
  "QtyIn" => "0"
]

Third:

array: [
  "QtyOut" => "0"
]

Now I want to check if QtyIn = 0, return A. QtyOut = 0, return B. And if QtyIn and QtyOut = 0, return C. I tried with 3 if statements like this:

if ( isset($data['QtyIn']) && isset($data['QtyOut']) ) {
    if ( $data['QtyIn'] <= 0 && $data['QtyOut'] <= 0 ) {
        return A
    }
} 

if ( isset($data['QtyIn']) ) {
    if ( $data['QtyIn'] <= 0 ) {
        return B
    }
}

if ( isset($data['QtyOut']) ) {
    if ( $data['QtyOut'] <= 0 ) {
        return C
    }
}

Is there anyway to write this code more clean?

Thank you!

1
  • Your code doesn't seem to test the conditions you say it tests. Commented Nov 2, 2020 at 7:00

3 Answers 3

1
if ( isset($data['QtyIn']) && isset($data['QtyOut']) ) {
    if ( $data['QtyIn'] == 0 && $data['QtyOut'] == 0 ) {
        return A;
    }else if ( $data['QtyIn'] == 0 ) {
        return B;
    }else if ( $data['QtyOut'] == 0 ) {
        return C
    }
} 
Sign up to request clarification or add additional context in comments.

Comments

1

If the first thing you do is to store the values in a temporary variable and apply ?? to set the value to some non-zero value if they are not set, then the tests become shorter...

function check($data)   {
    $in = $data['QtyIn'] ?? -1;
    $out = $data['QtyOut'] ?? -1;
    if ( $in == 0 && $out == 0 ) {
        return 'A';
    }
    if ( $in == 0 ) {
        return 'B';
    }
    
    if ( $out == 0 ) {
        return 'C';
    }
}
echo check(['QtyIn' => 0, 'QtyOut' => 0]);
echo check(['QtyIn' => 0]);
echo check(['QtyOut' => 0]);

You could shorten it using ternary expressions, but this isn't as readable (IMHO)...

function check($data)   {
    $in = $data['QtyIn'] ?? -1;
    $out = $data['QtyOut'] ?? -1;
    return ( $in == 0 && $out == 0 ) ? 'A' : 
        (( $in == 0 ) ? 'B' : 
                (( $out == 0 ) ? 'C' : ''));

}

This code also use == instead of <= 0 as @Jeto pointed out in his comment you state it must be = 0.

Comments

0

Cleaner doesn't mean shorter. If you want to be cleaner, for example, this way:

$qtyIn = $data['QtyIn'] ?? null;
$qtyOut = $data['QtyOut'] ?? null;

if (isZeroOrLess($qtyIn) && isZeroOrLess($qtyOut)) {
    return A;
}

if (isZeroOrLess($qtyIn)) {
    return B;
}

if (isZeroOrLess($qtyOut)) {
    return C;
}

function isZeroOrLess($val = null)
{
    if ($val === null) {
        return false;
    }
    return $val <= 0;
}

1 Comment

He asked for cleaner code only, no need to create functions I guess.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.