急求三元运算符的意义

WBOY
Release: 2016-06-13 12:59:32
Original
1137 people have browsed it

急求三元运算符的意思
function meth()
{
$a=$_POST["user"];
return isset($a) ? (is_array($a) ? $a : trim($a) : NULL;
}
麻烦解释下PHP里面这个三元运算符什么意思啊?
------解决方案--------------------

function meth()<br />
{<br />
	$a=$_POST["user"];<br />
<br />
	$rtval = '';<br />
	if(isset($a)){<br />
		if(is_array($a)){<br />
			$rtval = $a;<br />
		}else{<br />
			$rtval = trim();<br />
		}<br />
	}else{<br />
		$rtval = NULL;<br />
	}<br />
	<br />
	return $rtval;<br />
}
Copy after login

------解决方案--------------------
<br />
if(isset($a)){<br />
 if ((is_array($a)){<br />
    return $a;<br />
}else{<br />
return trim($a);<br />
} <br />
}else{<br />
 return NULL;<br />
}<br />
Copy after login

------解决方案--------------------
引用:
function meth()
{
$a=$_POST["user"];
return isset($a) ? (is_array($a) ? $a : trim($a) : NULL;
}
麻烦解释下PHP里面这个三元运算符什么意思啊?

少了一个反括号吧?
举个例子 求两者大的那个
$a=0; $b =1;
echo $a > $b(条件) ? $a(如果条件成立):$b(如果不成立);
输出 1;
------解决方案--------------------
<br />
//装B写法<br />
function meth()<br />
{<br />
$a=$_POST["user"];<br />
return isset($a) ? (is_array($a) ? $a : trim($a) : NULL;<br />
}<br />
<br />
//还原一下<br />
function meth()<br />
{<br />
 $a = $_POST["user"];<br />
 if( isset($a)){<br />
   if( is_array($a)) {<br />
          return $a;<br />
   }else {<br />
        return trim(a);<br />
   }<br />
}else {<br />
return null;<br />
}<br />
}<br />
<br />
<br />
Copy after login

简易简单的东西,简单点写,没必要折腾成那样。
第二个建议,函数里接收$_POST 参数,是很不人道的,函数应该做得更单纯些,就是对参数进行处理,保证参数全从入口得到。
第三个建议,就算要这样写,如果 不存在$_post['user']; 函数也挂了。 
建议原函数更改为
<br />
<br />
function meth()<br />
{<br />
<br />
return  isset($_POST["user"]) ? (is_array($_POST["user"]) ? $_POST["user"] : trim($_POST["user"]) : NULL;<br />
}<br />
return <br />
Copy after login

------解决方案--------------------
三元就是3个元素,
条件?结果1:结果2


两个问号是 "结果1"里面放了另外一个3元运算

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!