15

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?

If any of the trailing optional substrings are missing in the input string, the corresponding variables should be assigned a null value.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
MikeG
  • 1,205
  • 12
  • 19
  • 1
    `list` isn't a function. – Waleed Khan Mar 12 '13 at 15:33
  • 2
    "ignore" in the sense of "not assign anything" or in the sense of "assign null"? – Fabian Schmengler Mar 12 '13 at 15:35
  • You shouldn't be wanting this. When you define a variable by name in a scope, that variable should always be created. What should happen with the empty variables? Should they not be created? That'll mess up the following code... – deceze Mar 12 '13 at 15:35
  • 1
    I just want them to be null. BTW, the PHP community is much faster at answering these questions versus the Java people!! – MikeG Mar 12 '13 at 15:38

4 Answers4

53
list($user_id, $name, $limit, $remaining, $reset)
    = array_pad(explode('|', $user), 5, null);
ClemC
  • 614
  • 6
  • 14
deceze
  • 510,633
  • 85
  • 743
  • 889
19

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);
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
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().

SDC
  • 14,192
  • 2
  • 35
  • 48
0

sscanf() can do the same that list() + explode() (and array_pad()) can do except it is a single function call AND it can allow for type-specific casting of the substrings.

Code: (Demo with unit tests)

sscanf($test, '%d|%[^|]|%d|%d|%d', $user_id, $name, $limit, $remaining, $reset);

I find this to be a superior approach in every way versus the existing proposed solutions.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136