Is it better (safer/more readable) to use list or to assign values one after another ?

Examples :

With list :

$head = '';
if(strpos($data, "\r\n") !== false)
    list($status, $head) = explode("\r\n", $data, 2);
else
    $status = $data;

Without list :

$head = '';
$components = explode("\r\n", $data, 2);
$status = $components[0];

if(count($components) === 2) //Or isset($components[1])
    $head = $components[1];

What's the preferred way to write this piece of code ?

有帮助吗?

解决方案

Depending on the use case list may end up causing you problems. Conventionally defining the values however would not. Notes from http://PHP.net:

list() only works on numerical arrays and assumes the numerical indices start at 0.

.

Modification of the array during list() execution (e.g. using list($a, $b) = $b) results in undefined behavior.

.

. . .if you are using arrays with indices you usually expect the order of the indices in the array the same you wrote in the list() from left to right; which it isn't. It's assigned in the reverse order.

Clearly using list can cause some unexpected behavior, and it definitely isn't the most common way to do this. This makes list bad for readability because it's unconventional. As far as I know there are no benefits to using list , and I would assume that it is slower.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top