在php中,我经常需要使用数组来映射变量......但我似乎无法在一个内联中执行此操作.cf示例:
// the following results in an error:
echo array('a','b','c')[$key];
// this works, using an unnecessary variable:
$variable = array('a','b','c');
echo $variable[$key];
Run Code Online (Sandbox Code Playgroud)
这是一个小问题,但它每隔一段时间就会不停地窃听......我不喜欢这样一个事实:我没有使用变量;)
背景
在我定期使用的每种其他编程语言中,操作函数的返回值很简单,而不会声明一个新变量来保存函数结果.
但是,在PHP中,这看起来并不那么简单:
<?php
function foobar(){
return preg_split('/\s+/', 'zero one two three four five');
}
// can php say "zero"?
/// print( foobar()[0] ); /// <-- nope
/// print( &foobar()[0] ); /// <-- nope
/// print( &foobar()->[0] ); /// <-- nope
/// print( "${foobar()}[0]" ); /// <-- nope
?>
Run Code Online (Sandbox Code Playgroud)
<?php
function zoobar(){
// NOTE: casting (object) Array() has other problems in PHP
// see e.g., http://stackoverflow.com/questions/1869812
$vout = (object) Array('0'=>'zero','fname'=>'homer','lname'=>'simpson',);
return $vout;
}
// can php say "zero"? …Run Code Online (Sandbox Code Playgroud) 在某些语言中,如果函数返回一个数组,那么与将数组存储在变量中相反,然后检索单个元素,如下所示:
var someValues = getSomeValues();
var firstElement = someValues[0];
Run Code Online (Sandbox Code Playgroud)
您可以在函数调用之后直接使用数组索引表示法来检索返回数组的元素,如下所示:
var firstElement = getSomeValues()[0];
Run Code Online (Sandbox Code Playgroud)
这种结构或语法是什么?它有一个特殊的名字吗?
无法绕过这个......
说,我们像这样爆炸整个事情:
$ extract = explode('tra-la-la',$ big_sourse);
然后我们想要获得索引1的值:
$ finish = $ extract [1];
我的问题是如何一气呵成,这样说.与此类似的东西:
$ finish = explode('tra-la-la',$ big_sourse)[1]; //不起作用
像下面这样的东西会像魅力一样:
$ finish = end(explode('tra-la-la',$ big_sourse));
// 要么
$ finish = array_shift(explode('tra-la-la',$ big_sourse));
但是,如果价值位于中间某个位置怎么办?
arrays ×4
php ×3
syntax ×2
coding-style ×1
dereference ×1
explode ×1
function ×1
php-5.3 ×1
terminology ×1