0

Is it possible to put if statement inside an array like this

array(1 => 1, 2 => 2 if(!empty(3)){echo ", 3 => 3";}); 

instead of going

if(!empty(3)){ array (1 => 1, 2 => 2, 3 => 3); } else { array (1 =>1, 2 => 2); } 
5
  • 2
    Did you try it and see? Also, there are other options besides the one you showed for doing this. In PHP there's usually more than one way to do it. Commented Apr 20, 2017 at 12:15
  • some variable is intended here !empty(3) Commented Apr 20, 2017 at 12:16
  • As an (abhorrent) one-liner: [1 => 1, 2 => 2] + (!empty(3) ? [3 => 3] : []) Commented Apr 20, 2017 at 12:32
  • @deceze Why would this be abhorrent? Commented Apr 20, 2017 at 13:04
  • Bad readability. Explicit and easily readable should always trump terseness. Commented Apr 20, 2017 at 13:05

3 Answers 3

3

You could add the value after you created the array

$array = [1 => 1, 2 => 2]; if (...) { $array[3] = 3; } 

if you don't need the key, you could also just write

$array[] = 3; 
Sign up to request clarification or add additional context in comments.

Comments

1
$array = [ 1 => 1, 2 => 2 ]; if ( !empty(3) ) { $array[3] = 3; } 

Comments

0

You can use the conditional operator for value like below

$array = array( '1' => '1', '2' => '2', '3' => $cond ? '3' : '' ); 

if you need to add condition in key you can do below way

if ($cond) { $array[3] = 3; } 

you can also use array union operator or array_merge:

array('1' => '1') + ($cond ? array('3' => '3') : array()) array_merge(array('1' => '1'), $cond ? array('3' => '3') : array()) 

now you have to decide what is better for you.

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.