Reputation: 421
I have a string of data which is an unknown length eg $myvar = "data,data";
and i want to explode
the string eg list($a, $b) = explode(",", $myvar)
which works great if I know the length of the data, but im not sure how to handle variable lengths.
i was thinking of using if
statments.
eg: $letter_count = substr_count($myvar, ',');
if($letter_count == 2) { list($a, $b) = explode(",", $myvar) }
elseif($letter_count == 3) { list($a, $b, $c) = explode(",", $myvar) }
but this is not practical, anyone got any ideas how else i could do this?
Upvotes: 0
Views: 986
Reputation: 34062
If you use explode
, it will return an array that is split by your delimiter. You would then call each item by its index position. The following example uses a space as the delimiter.
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
Upvotes: 2
Reputation: 7134
just explode into a regular array reference:
$return = explode("," $myvar);
The format you're using is for...well...when you know what the expected output is.
Upvotes: 3