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.
There are three right ways of returning an array to a function: Using dynamically allocated array. Using static array. Using structure.
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.
We can also make a function return an array by declaring it inside a structure in C++.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With