2

I can't figure out why I get Parse error: syntax error, unexpected T_IF on line 6.

 $sf = array ( 

            "name" => $firstname . ' ' . $lastname,
            "email" => $email,
            "address" => $shipping_address_1 . if(!empty($shipping_address_2 )) { echo ", " . $shipping_address_2 }
            );
            print_r($sf);

I want to check if $shipping_address_2 is not empty, and if it's not, then display it.

1
  • 4
    Because the if statement is invalid there. Statements cannot be used inside expressions (apart from expression statements). Commented May 10, 2012 at 20:40

3 Answers 3

2

Because your code is wrong. You cannot put an if statement inside the array initialization.

Sign up to request clarification or add additional context in comments.

Comments

2

Not 100% sure, but you should be able to use a ternary operator...

"address" => $shipping_address_1 . 
    (!empty($shipping_address_2 )) ? 
        ", " . $shipping_address_2 : // This gets executed if condition is true
        ""    // This gets executed if the condition is false

4 Comments

Nitpick: It's a ternary operator and the conditional operator ;)
@Felix wow, never even heard the distinction before. Updated and thanks :)
I didn't know that either for a long time ;)
But since there is often only one ternary operator in programming languages, it can also be THE ternary operator.
1

Replace

 "address" => $shipping_address_1 . if(!empty($shipping_address_2 )) { echo ", " . $shipping_address_2 }

With

"address" => $shipping_address_1 . (empty($shipping_address_2) ? null :  ", " . $shipping_address_2)

Comments

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.