Skip to content
Advertisement

explode string into variables

Is there a way to explode a string into variables e.g

some_function($min, $max, "3, 20");

such that $min is assigned the value 3 and $max is assigned the value 20.

I know I can simply use

$data = explode("3, 20");

just wondering if there is another way.

Advertisement

Answer

PHP’s language construct list() can perform multiple assignments to variables (or even other array keys) by assigning an array.

list($min, $max) = explode(",", "3,20");

However, you would still need to apply a trim() to your variables since the $max value would have a leading space, or replace explode() with preg_split('/s*,s*/', $string) to split it on commas and surrounding whitespace.

Note: Use caution with list() to be sure that the array you’re assigning contains the same number of elements as list() has variables. They are assigned from right to left in PHP 5.x, not left to right, so if you happen to overwrite a variable on the left with its original contents on the right, you may get unexpected results. This is detailed with examples in the PHP docs.

Update for PHP 7: PHP 7 changes the assignment order behavior such that list() arguments are assigned from left to right

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement