0

In this scenario everything works as expected:

$someString = '1|2|3|4';
list($val1, $val2, $val3, $val4) = explode("|", $someString);

In the followin scenario there are more values in the $someString than what there are $vals to put them in:

$someString = '1|2|3|4|5|6';
list($val1, $val2, $val3, $val4) = explode("|", $someString);

How can I make it so that in the 2nd case the $val4 would be 4|5|6 instead of just 4, or how do I put these "leftovers" at the end of the $val4 without adding $val5, $val6 etc. so it would be 456?

Jani
  • 47
  • 7
  • 5
    `explode("|", $someString, 4)` [It's right there in the docs, man](http://php.net/manual/en/function.explode.php) – sjagr Nov 10 '14 at 17:27

2 Answers2

3

The PHP explode function can accept a third optional parameter called $limit:

If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string.

If the limit parameter is negative, all components except the last -limit are returned.

If the limit parameter is zero, then this is treated as 1.

So by that logic, you should use explode("|", $someString, 4):

$someString = '1|2|3|4|5|6';
list($val1, $val2, $val3, $val4) = explode("|", $someString, 4);
echo $val1; // 1
echo $val2; // 2
echo $val3; // 3
echo $val4; // 4|5|6
Community
  • 1
  • 1
sjagr
  • 15,983
  • 5
  • 40
  • 67
  • Thank you. I thought the limit would leave all the rest unnoted, but seems that is not the case. This is exactly what I was looking for. – Jani Nov 10 '14 at 17:45
1

In your specific case you can use the limiting clause of the explode function. In general though, there's not a clean way of catching the "leftovers" of a list() assignment although we can make it work.

The documentation of list() says that the return value is the assigned array.

For example:

$arr = array('a', 'b', 'c', 'd', 'e');
var_dump(list($a, $b, $c) = $arr);
/*
array(5) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  string(1) "e"
}
*/

var_dump($a, $b, $c);
/*
string(1) "a"
string(1) "b"
string(1) "c"
*/

We can exploit this with array_slice() to extract the leftovers and do the assignment at the same time:

$leftovers = array_slice( list($a, $b, $c) = $arr, 3);

This has the same effect as doing:

$temp = operation_to_build_array();

list($a, $b, $c) = $temp;
$leftovers = array_slice($temp, 3);
Mr. Llama
  • 20,202
  • 2
  • 62
  • 115