2

Possible Duplicate:
Access array element from function call in php

instead of doing this:

$s=explode('.','hello.world.!');
echo $s[0]; //hello

I want to do something like this:

echo explode('.','hello.world.!')[0];

But doesn't work in PHP, how to do it? Is it possible? Thank you.

Community
  • 1
  • 1
Reacen
  • 2,312
  • 5
  • 23
  • 33

8 Answers8

3

Currently not but you could write a function for this purpose:

function arrayGetValue($array, $key = 0) {
    return $array[$key];
}

echo arrayGetValue(explode('.','hello.world.!'), 0);
str
  • 42,689
  • 17
  • 109
  • 127
3

As the oneliners say, you'll have to wait for array dereferencing to be supported. A common workaround nowadays is to define a helper function for that d($array,0).

In your case you probably shouldn't be using the stupid explode in the first place. There are more appropriate string functions in PHP. If you just want the first part:

echo strtok("hello.world.!", ".");
mario
  • 144,265
  • 20
  • 237
  • 291
3

It's not pretty; but you can make use of the PHP Array functions to perform this action:

$input = "one,two,three";

// Extract the first element.
var_dump(current(explode(",", $input)));

// Extract an arbitrary element (index is the second argument {2}).
var_dump(current(array_slice(explode(",", $input), 2, 1)));

The use of array_slice() is pretty foul as it will allocate a second array which is wasteful.

NullUserException
  • 83,810
  • 28
  • 209
  • 234
JonnyReeves
  • 6,119
  • 2
  • 26
  • 28
2

Not at the moment, but it WILL be possible in later versions of PHP.

2

While it is not possible, you technically can do this to fetch the 0 element:

echo array_shift(explode('.','hello.world.!'));

This will throw a notice if error reporting E_STRICT is on.:
Strict standards: Only variables should be passed by reference

afuzzyllama
  • 6,538
  • 5
  • 47
  • 64
2

This will be possible in PHP 5.4, but for now you'll have to use some alternative syntax.

For example:

list($first) = explode('.','hello.world.!');
echo $first;
Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
1

nope, not possible. PHP doesn't work like javascript.

gargantuan
  • 8,888
  • 16
  • 67
  • 108
1

No, this is not possible. I had similar question before, but it's not

genesis
  • 50,477
  • 20
  • 96
  • 125