Reputation: 9173
I need to add an element to an array only if a condition is met.
I want to add an element of a given needle exists in a haystack.
The following is the traditional way of doing it.
if(in_array($options_array[$i], $meta_info_keys))
{
$array = append_to();
}
Upvotes: 0
Views: 248
Reputation: 76646
Use a ternary expression:
expr1 ? expr2 : expr3;
Which means:
if expr1 then expr2 otherwise expr3
Visualization:
Your statement can be rewritten as:
$array = (in_array($options_array[$i], $meta_info_keys)) ? append_to() : $array;
It's generally recommended to avoid ternary statements if they make your code unreadable. In this case, it doesn't really matter, though.
Upvotes: 3
Reputation: 4194
Something like this:
$array = in_array($options_array[$i], $meta_info_keys) ? append_to() : $array;
Upvotes: 0