判断是否为空之后的操作

WBOY
Release: 2016-06-23 13:50:09
Original
813 people have browsed it

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


回复讨论(解决方案)

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

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

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

$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;}
Copy after login

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

$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);
Copy after login

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!