0

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(); } 

2 Answers 2

3

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.

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

2 Comments

Wont this clear out the array if the condition is false?
@RyanS: That was not what I meant. Updated the answer.
0

Something like this:

$array = in_array($options_array[$i], $meta_info_keys) ? append_to() : $array;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.