I have several functions that return multidimensional arrays and most of the time I don’t need all of the info returned in the array…only some of it. So I find myself writing code similar to the following:
myVar = someFunction();
myVar = myVar[someIndex];
Is there any way to combine this into one line? i.e.
myVar = ( someFunction() )[someIndex];
You can do that in PHP 5.3
I’m using 5.3. What should the correct syntax be? I get a parse error if I use the syntax given in my example…
fristi
February 18, 2010, 10:23pm
4
I’m not a PHP 5.3 specialist, actually haven’t used it yet Didn’t have an opurtunity…
The thing that you describe is something I know from Perl, zhere it is possible to take parts of arrays that way, and in there they call it slicing.
So my PHP search on slicing turned up the follozing function:
array_slice ( array $array , int $offset [, int $length [, bool $preserve_keys = false ]] )
so maybe this will work for you (untested):
$myVar = array_slice(someFunction(), $someIndex);
I was sure it was added to PHP 5.3, but now I can’t find anything about it.
Maybe I was mistaking it for this .
fristi
February 18, 2010, 10:34pm
6
Other idea that just popped into my head is to pass the index to the function like this:
function myfunction($param1, $param2, $Index = NULL)
{
/* your code*/
return ($index === NULL) ?
$array :
$array[$index]
}
$var = myfunction($param1, $param2, $Index = 3);
@fristi , that would work, but hopefully there is a way that doesn’t require me to make any changes to the actual functions…