Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

explode without variables [duplicate]

Tags:

php

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.

like image 566
Reacen Avatar asked Mar 09 '26 08:03

Reacen


2 Answers

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.!", ".");
like image 198
mario Avatar answered Mar 10 '26 21:03

mario


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);
like image 25
str Avatar answered Mar 10 '26 20:03

str



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!