Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing an array element when returning from a function

Some searching through Google (and my own experience) shows that in PHP you can't grab an array element when it's been returned from a function call on the same line. For example, you can't do:

echo getArray()[0];

However, I've come across a neat little trick:

echo ${!${false}=getArray()}[0];

It actually works. Problem is, I don't know why it works. If someone could explain, that would be great.

Thanks.

like image 217
Daniel Avatar asked Sep 04 '10 13:09

Daniel


People also ask

How do you return an array element from a function?

There are three right ways of returning an array to a function: Using dynamically allocated array. Using static array. Using structure.

How do you access the elements of an array?

Access Array Elements You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

Can a function have an array as a return type?

We can also make a function return an array by declaring it inside a structure in C++.


2 Answers

echo ${!${false}=getArray()}[0];

This is how it works, step by step

${false}=getArray()

assigns the result of getArray to a variable with an empty name ('' or null would work instead of false)

!${false}=getArray()

negates the above value, turning it to boolean false

 ${!${false}=getArray()}

converts the previous (false) value to an (empty) string and uses this string as a variable name. That is, this is the variable from the step 1, equal to the result of getArray.

${!${false}=getArray()}[0];

takes index of that "empty" variable and returns an array element.

Some more variations of the same idea

echo ${1|${1}=getArray()}[1];
echo ${''.$Array=getArray()}[1];

function p(&$a, $b) { $a = $b; return '_'; }
echo ${p($_, getArray())}[1];

As to why getArray()[0] doesn't work, this is because php team has no clue how to get it to work.

like image 198
user187291 Avatar answered Nov 15 '22 17:11

user187291


it works because your using the braces to turn the value into a varialbe, heres an example.

$hello = 'test';
echo ${"hello"};

Why is this needed, this is needed encase you want to turn a string or returned value into a variable, example

${$_GET['var']} = true;

This is bad practise and should never be used IMO.

you should use Objects if you wish to directly run off functions, example

function test()
{
   $object = new stdClass();
   $object->name = 'Robert';

   return $object;
}
echo test()->name;
like image 36
RobertPitt Avatar answered Nov 15 '22 17:11

RobertPitt