CrazeD
CrazeD

Reputation: 535

Is there a way to return an array key from a function in one line?

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

Answers (3)

Indranil
Indranil

Reputation: 2471

Try this

list($one, $two, $three) = explode('-', $str);

or

foreach($one as $number) {
    $$number = $number;
}

for a larger array...

Upvotes: 2

mario
mario

Reputation: 145492

You could also use the right function for the job:

 $one = strtok($str, "-");

See strtok() or strstr() with third parameter.

Upvotes: 2

Michael Berkowski
Michael Berkowski

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

Related Questions