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.

4
  • 1
    list isn't a function. Commented Mar 12, 2013 at 15:33
  • 2
    "ignore" in the sense of "not assign anything" or in the sense of "assign null"? Commented Mar 12, 2013 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... Commented Mar 12, 2013 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!! Commented Mar 12, 2013 at 15:38

4 Answers 4

55
list($user_id, $name, $limit, $remaining, $reset)
    = array_pad(explode('|', $user), 5, null);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.