2011-08-28 59 views

回答

3

随着oneliners说,你必须等待数组语法得到支持。现在常见的解决方法是为该d($array,0)定义一个辅助函数。

在你的情况下,你可能不应该首先使用愚蠢的explode。 PHP中有更合适的字符串函数。如果你只想要第一部分:

echo strtok("hello.world.!", "."); 
1

不可能。 PHP不能像JavaScript一样工作。

1

不,这是不可能的。我之前有过类似的问题,但它不是

+0

不可能是什么;) – JonnyReeves

3

目前没有,但你可以编写一个函数用于此目的:

function arrayGetValue($array, $key = 0) { 
    return $array[$key]; 
} 

echo arrayGetValue(explode('.','hello.world.!'), 0); 
2

虽然这是不可能的,你在技术上可以做到这一点,以获取0元:

echo array_shift(explode('.','hello.world.!')); 

这将引发一个通知,如果错误报告E_STRICT上:
Strict standards: Only variables should be passed by reference

+1

可以使用'echo current(explode('。','hello.world。!' ));'不会引发E_STRICT消息。 – Gordon

+0

我从来没有真正使用'current()'和'end()'函数,但我可能应该再次查看它们。 – afuzzyllama

+0

足够有趣,end()确实会提升E_STRICT – Gordon

2

这将是可能的在PHP 5.4,但现在你将不得不使用一些替代语法。

例如:

list($first) = explode('.','hello.world.!'); 
echo $first; 
3

这不是很漂亮;但你可以利用PHP Array functions来执行此操作:

$input = "one,two,three"; 

// Extract the first element. 
var_dump(current(explode(",", $input))); 

// Extract an arbitrary element (index is the second argument {2}). 
var_dump(current(array_slice(explode(",", $input), 2, 1))); 

使用的array_slice()很臭,因为它会分配第二阵列是一种浪费。

+0

+1,因为它能够访问第n个元素。我从来没有想过这样做! – afuzzyllama

+0

does current()与非变量一起工作吗? – arnaud576875

+1

以上代码在CLI上由PHP 5.3.6成功执行。 – JonnyReeves