Home > Mobile >  key value array - set value if set and equal to specific value
key value array - set value if set and equal to specific value

Time:04-11

Can I set a value of an array by checking if it's both set and equal to some value in the same line?

i.e.

$input = $_REQUEST['input'];

$arr = [
'field' => // set field to the $input value if it's set and equal to "some_value", otherwise set to null
];

CodePudding user response:

This should be what you're looking for...

$arr = [
'field' => isset($_REQUEST['input']) && $_REQUEST['input'] === 'some_value' ? $_REQUEST['input'] : null
];

We can use the ternary operator so the above is essentially the same as:

$arr = [];

if (isset($_REQUEST['input']) && $_REQUEST['input'] === 'some_value') {
  $arr['field'] = $_REQUEST['input'];
} else {
  $arr['field'] = null;
}

Alternatively, another approach is (if using PHP >8)...

$input = $_REQUEST['input'] ?? null;
$arr = [
  'field' => $input === 'some_value' ? $input : null
];

CodePudding user response:

 $input = $_REQUEST['input'];
    $arr = [
    'field' => isset($input) ? $input : null
    ];

You can use the ternary operator

  •  Tags:  
  • php
  • Related