发布日期:2018-03-26
如何从函数中返回多个值?+ 查看更多
如何从函数中返回多个值?
+ 查看更多
发布日期:2018-03-26 11:22
分类:PHP
浏览次数:73
一个函数可以有2个返回值吗?
function test($testvar) { // do something return $var1; return $var2; }
回答:
函数不能直接返回2个变量。
1. 设置条件返回不同的变量。例如,条件 $blahblah === true 满足时,返回 $var2
function wtf($blahblah = true) { $var1 = "ONe"; $var2 = "tWo"; if($blahblah === true) { return $var2; } return $var1; } echo wtf(); //would echo: tWo echo wtf("not true, this is false"); //would echo: ONe2. 通过数组返回2个变量.
function wtf($blahblah = true) { $var1 = "ONe"; $var2 = "tWo"; if($blahblah === true) { return $var2; } if($blahblah == "both") { return array($var1, $var2); } return $var1; } echo wtf("both")[0] //would echo: ONe echo wtf("both")[1] //would echo: tWo list($first, $second) = wtf("both") // value of $first would be $var1, value of $second would be $var2