Access array values ​​without square brackets in php

In php, how can I access array values ​​without using square brackets around the key? My problem is that I want to access the array elements returned by the function. The Say (args) function returns an array. Why $ var = function (args) [0]; yelling at me about square brackets? Can I do something like $ var = function (args) .value (0); or am I missing something very basic?

+7
arrays php square-bracket
source share
5 answers

As others have said, you pretty much have to use a temporary variable:

$temp = myFunction(); $value = $temp[0]; 

But, if you know the structure of the returned array, you can avoid the temporary variable.

If you need only the first element:

 $value = reset(myFunction()); 

If you want to use the last element:

 $value = end(myFunction()); 

If you need any of them:

 // second member list(, $value) = myFunction(); // third list(, , $value) = myFunction(); // or if you want more than one: list(, , $thirdVar, , $fifth) = myFunction(); 
+10
source share

In PHP, when you get an array as the result of a function, you unfortunately need to take 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; 

(assuming function returns an object, of course.)

+2
source share
 function getKey($array, $key){ return $array[$key]; } $var = getKey(myFunc(args), $key); 

It is impossible to do this without adding a custom function, unfortunately. This is simply not part of the syntax.

You can always just do it the old way.

 $array = myFunc(); $value = $array[0]; 
+1
source share

Which exactly matches your expectation:

 echo pos(array_slice($a=myFunc(), pos(array_keys(array_keys($a), 'NameOfKey')); 

answered Kinetics Kin, Taipei

+1
source share

if you want this, it is probably best to return an object (unfortunately its completely lame php doesn't support this). Heres a crazy way that I was able to figure out, but out of novelty (please don't do this!):

 function returnsArray(){ return array("foo" => "bar"); } echo json_decode(json_encode((object)returnsArray()))->foo; //prints 'bar' 

So yes ... if they don't add support for dereferencing arrays in php, I think you should probably just pass the returned array as an object:

 return (object)array("foo" => "bar"); 

and then you can do returnArray () -> foo, since php relaxes dereferencing for objects, but not arrays .. or, of course, write a wrapper as others have suggested.

+1
source share

All Articles