In php how can I access an array's values without using square brackets around the key? My particular problem is that I want to access the elements of an array returned by a function. Say function(args) returns an array. Why is $var = function(args)[0]; yelling at me about the square brackets? Can I do something like $var = function(args).value(0); or am I missing something very basic?
+1
A:
In PHP, when getting an array as a function result, you unfortunately have to do an extra step:
$temp_array = function($args);
$var = $temp_array[0];
For objects, this has been relaxed in PHP 5. You can do:
$echo function($args)->property;
(provided function
returns an object of course.)
Pekka
2010-03-23 01:21:05
It sucks but this is the only way to do this. One of the many reasons to hate PHP.
Luke Magill
2010-03-23 01:21:56
@Luke true, but not *that* bad imo. Who knows, it may get fixed in PHP 7 :)
Pekka
2010-03-23 01:23:00
@Luke - that's a bit strong isn't it?
nickf
2010-03-23 01:25:11
A:
function getKey($array, $key){
return $array[$key];
}
$var = getKey(myFunc(args), $key);
There is no way to do this without adding a user function unfortunately. It is just not part of the syntax.
You could always just do it the old fashion way
$array = myFunc();
$value = $array[0];
Chacha102
2010-03-23 01:21:19
+6
A:
As the others have said, you pretty much have to use a temporary variable:
$temp = myFunction();
$value = $temp[0];
But, if know the structure of the array being returned it is possible to avoid the temporary variable.
If you just want the first member:
$value = reset(myFunction());
If you want the last member:
$value = end(myFunction());
If you want any one in between:
// second member
list(, $value) = myFunction();
// third
list(, , $value) = myFunction();
// or if you want more than one:
list(, , $thirdVar, , $fifth) = myFunction();
nickf
2010-03-23 01:28:23
reset() and end() require the arguments be references. You get an E_STRICT notice in recent versions of php.
chris
2010-03-23 01:43:08
yes, i have been doing this with temporary variables, but was wondering whether i really needed to. now i'm just wondering _why_ i have to. but in any case your list() usage is pretty clever. thanks!
amb
2010-03-23 05:27:17
A:
What exactly matches your expecting is:
echo pos(array_slice($a=myFunc(), pos(array_keys(array_keys($a), 'NameOfKey'));
answered Kinetix Kin, Taipei
Kinetix Kin
2010-10-25 14:41:10