Adrian
Adrian

Reputation: 2656

unexpected T_IF, if statement in array

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.

Upvotes: 2

Views: 151

Answers (3)

Baba
Baba

Reputation: 95131

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)

Upvotes: 1

Jeff Lambert
Jeff Lambert

Reputation: 24661

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

Upvotes: 2

user267885
user267885

Reputation:

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

Upvotes: 2

Related Questions