views:

87

answers:

2

Hey all,

I'm looking to see if there is some PHP syntax that I'm missing that will allow me to grab the contents of the array I just manipulated using a function..

Good example:

$firstElement = sort($myArray)[0];

Where normally I would have to do this:

$myArray = sort($myArray);
$firstElement = $myArray[0];

Any clean way of doing this??

Thanks Everyone! Matt

+3  A: 

There is no syntax to access an array value if it’s not in a variable. There was a proposal to add such a syntax but it was declined.

PS: sort does only return boolean values. So your example wouldn’t work anyway.

Gumbo
Ah ok. Well I had different code - but I thought it might make more sense to show sort :-/. Ha guess not.
Matt
+2  A: 

A syntax like this one

$firstElement = sort($myArray)[0];

is definitly nont possible -- you have noticed that yourself ^^

If you are willing to get the first element of an array, you could use the reset function, like this :

$list = array('z', 'c', 'd');
$element = reset($list);
var_dump($element);

It would display :

string 'z' (length=1)

The side-effect is that (quote) :

reset() rewinds array 's internal pointer to the first element and returns the value of the first array element.

Btw, as sort doesn't return the array, you cannont do that :

$list = array('z', 'c', 'd');
$element = reset(sort($list));
var_dump($element);

It would give a warning :

Warning: reset() [function.reset]: Passed variable is not an array or object

Pascal MARTIN
Ah yah. I wanted an example that was easy to understand but it looks like I messed that one up :-/. Yah that's a little more confusing and verbose than my alternative method. I was just wondering if I missed something along my PHP journey that would make it quicker! Thanks though!
Matt
Well, the solution you proposed in your question is the one I actually always use ^^ But was fun to think about another one anyway ^^
Pascal MARTIN