MikeG
MikeG

Reputation: 1275

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

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.

Upvotes: 16

Views: 5144

Answers (4)

mickmackusa
mickmackusa

Reputation: 47894

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.

Upvotes: 0

deceze
deceze

Reputation: 522042

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

Upvotes: 55

Mark Baker
Mark Baker

Reputation: 212412

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);

Upvotes: 19

SDC
SDC

Reputation: 14222

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

Upvotes: 5

Related Questions