Parse a pipe-delimited string into 2, 3, 4 or 5 variables (depending on the input string)
Asked Answered
I

4

16

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.

Irreversible answered 12/3, 2013 at 15:31 Comment(4)
list isn't a function.Implicate
"ignore" in the sense of "not assign anything" or in the sense of "assign null"?Cheesewood
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...Lili
I just want them to be null. BTW, the PHP community is much faster at answering these questions versus the Java people!!Irreversible
C
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().

Candelabrum answered 12/3, 2013 at 15:33 Comment(0)
L
55
list($user_id, $name, $limit, $remaining, $reset)
    = array_pad(explode('|', $user), 5, null);
Lili answered 12/3, 2013 at 15:36 Comment(0)
I
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);
Irreligious answered 12/3, 2013 at 15:42 Comment(0)
C
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().

Candelabrum answered 12/3, 2013 at 15:33 Comment(0)
A
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.

Amortizement answered 23/4, 2023 at 12:42 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.