3

I'm just looking to optimize the code below. It works, but I want to see if anyone has a shorter way of writing the following condition:

if(
!empty($_REQUEST['shipping_fname']) || 
!empty($_REQUEST['shipping_lname']) || 
!empty($_REQUEST['shipping_address1']) || 
!empty($_REQUEST['shipping_address2']) || 
!empty($_REQUEST['shipping_city']) || 
!empty($_REQUEST['shipping_state']) ||
!empty($_REQUEST['shipping_zip']) ||
!empty($_REQUEST['shipping_country'])){

        /* do stuff in here */

}

As you can see, there are some Request variables I'm checking for. If any of them are not empty, then I'd continue the rest. (for those who have to know, if any shipping info is passed, I'll do validation inside the brackets. Sometimes someone sends just the first, last, and zip.

Again, it works, just wondering if anyone has a shorter methodology.

1 Answer 1

2

It will be worse performance, and really I would probably just stick with your way, but a less burdensome alternative might be:

$arr = array('shipping_fname', 'shipping_lname', '...');
$go = false;
foreach ($arr as $f) { if (!empty($_REQUEST[$f])) { $go = true; break; } }
if ($go) { ... }

You could also do away with the $go if you wanted:

$arr = array('shipping_fname', 'shipping_lname', '...');
foreach ($arr as $f) {
    if (!empty($_REQUEST[$f])) {
        /* do stuff in here */
        break;
    } 
}
Sign up to request clarification or add additional context in comments.

3 Comments

you make a good point. If my way is better for performance, I'll just suck it up. But I do like your array() alternative.
It's going to barely be slower. Like, maybe a nano second slower. And @tq what in the world are you talking about? How does in_array help here?
in_arra() not work because he check independent key of $_REQUEST

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.