Home  >  Article  >  Backend Development  >  判断是否为空之后的操作

判断是否为空之后的操作

WBOY
WBOYOriginal
2016-06-23 13:50:09793browse

判断$a、$b、$c、$d是否为空,如果不为空,在每个相邻变量间加逗号,如果只有一个不为空,则不加逗号,空变量不输出。
用if太复杂,有没有简便的写法?麻烦举个例,谢谢!


回复讨论(解决方案)

简便的办法不知道
用if有什么不好吗?

$buf = array($a, $b, $c, $d);echo join(',', array_filter($buf, 'cmp'));function cmp($m) {  return ! empty($m);}

$s = "$a,$b,$c,$d";$ar = preg_split('/,/', $s, -1, PREG_SPLIT_NO_EMPTY);echo implode(',', $ar);

$a = 'a';$b = '';$c = '';$d = 'd';echo handle($a,$b,$c,$d);function handle($a,$b,$c,$d){    $arr = array();    array_push($arr, $a,$b,$c,$d);    $ret = trim(implode(',', $arr),',');    $ret = preg_replace('/[,]{2,}/', ',', $ret);    return $ret;}

修改了一下,刚才那个没有考虑变量中含有","的情况。

$a = 'a';$b = 'b';$c = 'c';$d = 'd';$arr = array($a,$b,$c,$d);$ret = array();foreach($arr as $val){    if($val!=''){        array_push($ret, $val);    }}echo implode(',', $ret);

Statement:
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