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,212
  • 5
  • 22
  • 32

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
  • 38,402
  • 15
  • 99
  • 123
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
  • 141,508
  • 20
  • 234
  • 284
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
  • 81,190
  • 27
  • 202
  • 228
JonnyReeves
  • 6,009
  • 2
  • 25
  • 28
2

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

Tim Cooper
  • 151,519
  • 37
  • 317
  • 271
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,453
  • 5
  • 45
  • 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
  • 95,062
  • 22
  • 198
  • 192
1

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

gargantuan
  • 8,790
  • 14
  • 64
  • 107
1

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

genesis
  • 49,367
  • 20
  • 94
  • 122