PHP列表函数的可选参数

时间:2022-01-03 08:08:53

I have a line like this in my code:

我的代码中有这样一行:

list($user_id, $name, $limit, $remaining, $reset) = explode('|', $user);

The last 3 parameters may or may not be there. Is there a function similar to list that will automatically ignore those last parameters if the array is smaller than expected?

最后3个参数可能存在,也可能不存在。如果数组小于预期,是否有一个类似list的函数会自动忽略最后的参数?

3 个解决方案

#1


5  

Just add some spare pipes to the end of the string:

只要在绳子的末端加上一些备用的管子就可以了:

list($user_id, $name, $limit, $remaining, $reset) = explode('|', $user.'||||');

problem solved.

问题解决了。

Note: If you're loading arbitrary pipe-delimited data, you might want to use str_getcsv() function rather than explode().

注意:如果您正在加载任意的管道分隔数据,您可能希望使用str_getcsv()函数而不是爆炸()。

#2


28  

list($user_id, $name, $limit, $remaining, $reset)
    = array_pad(explode('|', $user), 5, null);

#3


7  

If you're concerned that SDC's solution feels "hacky"; then you can set some default values and use:

如果你担心SDC的解决方案会让你觉得“陈腐”;然后可以设置一些默认值并使用:

$user = '3|username';

$defaults = array(NULL, NULL, 10, 5, FALSE);
list($user_id, $name, $limit, $remaining, $reset) = explode('|', $user) + $defaults;

var_dump($user_id, $name, $limit, $remaining, $reset);

#1


5  

Just add some spare pipes to the end of the string:

只要在绳子的末端加上一些备用的管子就可以了:

list($user_id, $name, $limit, $remaining, $reset) = explode('|', $user.'||||');

problem solved.

问题解决了。

Note: If you're loading arbitrary pipe-delimited data, you might want to use str_getcsv() function rather than explode().

注意:如果您正在加载任意的管道分隔数据,您可能希望使用str_getcsv()函数而不是爆炸()。

#2


28  

list($user_id, $name, $limit, $remaining, $reset)
    = array_pad(explode('|', $user), 5, null);

#3


7  

If you're concerned that SDC's solution feels "hacky"; then you can set some default values and use:

如果你担心SDC的解决方案会让你觉得“陈腐”;然后可以设置一些默认值并使用:

$user = '3|username';

$defaults = array(NULL, NULL, 10, 5, FALSE);
list($user_id, $name, $limit, $remaining, $reset) = explode('|', $user) + $defaults;

var_dump($user_id, $name, $limit, $remaining, $reset);