Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional parameters to PHP list function

Tags:

arrays

php

tuples

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?

like image 804
MikeG Avatar asked Mar 12 '13 15:03

MikeG


2 Answers

list($user_id, $name, $limit, $remaining, $reset)
    = array_pad(explode('|', $user), 5, null);
like image 128
deceze Avatar answered Nov 14 '22 15:11

deceze


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);
like image 29
Mark Baker Avatar answered Nov 14 '22 17:11

Mark Baker