'key value array - set value if set and equal to specific value
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
];
Solution 1:[1]
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
];
Solution 2:[2]
$input = $_REQUEST['input'];
$arr = [
'field' => isset($input) ? $input : null
];
You can use the ternary operator
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Levi Cole |
Solution 2 | Arun Vitto |