简体   繁体   English

直接从PHP中的方法调用中从数组中获取元素

[英]Get an element from an array directly from the method call in PHP

In Java you can get an element from an array directly from the method call, like this: 在Java中,您可以直接从方法调用中从数组中获取元素,如下所示:

System.out.println(PrintArrayOfStrings()[0]);

Is there any similar way to do this in PHP? 有没有类似的方法在PHP中执行此操作?

echo PrintArrayOfStrings()[0]; // Does not work!

Or do I always have to use a variable that first gets the array and then I use that variable to get the element? 还是我总是必须先使用一个变量来获取数组,然后再使用该变量来获取元素?

$array = PrintArrayOfStrings();
echo $array[0]; // Works!
echo PrintArrayOfStrings()[0]; 

is not possible/supported in PHP. 在PHP中不可能/不受支持。

You can do it as you wrote: 您可以按照以下方式执行此操作:

$array = PrintArrayOfStrings();
echo $array[0];

or do it like this, if you want to have it on one line: 或这样做,如果您想将其放在一行上:

function get($array, $key){
    return $array[$key];
}

so then, you can use: 那么,你可以使用:

echo get(PrintArrayOfStrings(), 0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM