Reputation: 535
For example:
$str = 'one-two-three';
$one = explode('-', $str);
Is there a way to make $one equal to "one" without doing $one = $one[0]
?
Upvotes: 1
Views: 72
Reputation: 2471
Try this
list($one, $two, $three) = explode('-', $str);
or
foreach($one as $number) {
$$number = $number;
}
for a larger array...
Upvotes: 2
Reputation: 145492
You could also use the right function for the job:
$one = strtok($str, "-");
See strtok()
or strstr()
with third parameter.
Upvotes: 2
Reputation: 270707
Sure, use list()
:
list($one,$two,$three) = explode('-', $str);
echo $one;
// one
list()
for multi-assignment isn't quite as nice as being able to dereference an array element directly from a function call, or as convenient as Python's multi-assignment, but it does the job.
In PHP 5.4, we'll be able to dereference directly from the function call, as in:
// Coming in 5.4...
explode("-", $str)[0]
Upvotes: 3