Optional parameters to PHP list function

后端 未结 3 963
隐瞒了意图╮
隐瞒了意图╮ 2020-12-16 18:47

I have a line like this in my code:

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

The last 3 parameters may or

相关标签:
3条回答
  • 2020-12-16 19:04
    list($user_id, $name, $limit, $remaining, $reset)
        = array_pad(explode('|', $user), 5, null);
    
    0 讨论(0)
  • 2020-12-16 19:09

    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().

    0 讨论(0)
  • 2020-12-16 19:21

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

    $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);
    
    0 讨论(0)
提交回复
热议问题