Answer the question
In order to leave comments, you need to log in
How is it more readable or correct to write a ternary operation in return if arrays are returned in two cases?
one)
return (empty($error)) ?
[ 'data' => $data,
'status' => 'success',
'message' => 'Done'
]
:
[ 'data' => $errors,
'status' => 'error',
'message' => $message
];
return (empty($error)) ?[
'data' => $data,
'status' => 'success',
'message' => 'Done'
] : [
'data' => $errors,
'status' => 'error',
'message' => $message
];
Answer the question
In order to leave comments, you need to log in
IMHO the ternary operator is useful when it is written in one line.
Otherwise, it's easier, more useful, and clearer to use a regular if.
As for me, the most readable and correct option is:
if (!empty($errors)) {
return [
'data' => $errors,
'status' => 'error',
'message' => $message,
];
}
return [
'data' => $data,
'status' => 'success',
'message' => 'Done',
];
$status = 'success';
$message = 'Done';
// ...
if (!empty($errors)) {
$data = $errors;
$status = 'error';
}
return [
'data' => $data,
'status' => $status,
'message' => $message,
];
Many different options can be written, but both initial ones are somehow not very readable. 27cm wrote good. You can also do this:
$response = [
'data' => $data,
'status' => 'success',
'message' => 'Done'
];
if (!empty($error)) {
// можно через array_merge еще написать
$response = [
'data' => $errors,
'status' => 'error',
'message' => $message,
];
}
return $response;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question