M
M
Maxim Zahlupa2015-10-19 19:14:40
PHP
Maxim Zahlupa, 2015-10-19 19:14:40

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
      ];

2)
return (empty($error)) ?[
  'data'    => $data,
  'status'  => 'success',
  'message' => 'Done'
] : [
  'data'    => $errors,
  'status'  => 'error',
  'message' => $message
];

or write your own.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Saboteur, 2015-10-19
@saboteur_kiev

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.

C
Cat Anton, 2015-10-19
@27cm

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',
];

Or like this:
$status = 'success';
$message = 'Done';

// ...

if (!empty($errors)) {
    $data = $errors;
    $status = 'error';
}

return [
    'data'    => $data,
    'status'  => $status,
    'message' => $message,
];

But I would not call any of your options with the ?: operator readable in this case.

A
Alexander Kubintsev, 2015-10-19
@akubintsev

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 question

Ask a Question

731 491 924 answers to any question