Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to index a returned array?

Tags:

php

function returnsAnArray ()
{
  return array ('test');
}

echo returnsAnArray ()[0];

generates a syntax error in PHP. What's the most efficient way to directly obtain an element from a returned array without assigning the result to a temp variable?

like image 325
Jeroen van Delft Avatar asked Oct 05 '08 20:10

Jeroen van Delft


4 Answers

Here's one way, using the list language construct

function returnsAnArray ()
{
  return array ('test');
}

list($foo)=returnsAnArray();

You could grab a sequence of elements from an offset by combining this with array_slice

list($third,$fourth,$fifth)=array_slice(returnsAnArray(), 2, 3);
like image 65
Paul Dixon Avatar answered Oct 31 '22 17:10

Paul Dixon


Define a new function for returning a specific index from an array.

function arr_index($arr, $i) { return $arr[$i]; }

You might want to add some error and type checking there.

And then use it like this:

echo arr_index(returnsAnArray(), 0);

Happy Coding :)

like image 36
pmg Avatar answered Oct 31 '22 19:10

pmg


This will work if there is only one member in the array:

 <?php
 echo current(returnsAnArray());
 ?>
like image 22
Eran Galperin Avatar answered Oct 31 '22 19:10

Eran Galperin


Another option:

<?php
echo reset(functionThatReturnsAnArray());
?>

Similar thread: PHP: Can I reference a single member of an array that is returned by a function?

like image 42
Darryl Hein Avatar answered Oct 31 '22 17:10

Darryl Hein