Search code examples
phparraystext-parsingvariable-declarationdelimited

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.


Solution

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