For example:
$str = 'one-two-three';
$one = explode('-', $str);
Is there a way to make $one equal to "one" without doing $one = $one[0]
?
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]
You could also use the right function for the job:
$one = strtok($str, "-");
Try this
list($one, $two, $three) = explode('-', $str);
or
foreach($one as $number) {
$$number = $number;
}
for a larger array...