如何使用null效果连接php中的各种字符串

Dee*_*ain 3 php string concatenation string-concatenation

我有四个php变量,如:$abc, $bcd, $dsf, $gkg.现在我想用逗号分隔它们来连接它们.

输出:

abc,bcd,dsf,gkg
Run Code Online (Sandbox Code Playgroud)

现在,如果任何变量没有返回任何值..那么输出就像这样:

abc,,dsf,gkg
Run Code Online (Sandbox Code Playgroud)

那么如果任何变量的值为null,该怎么做才能避免这种情况?

$street = tribe_get_address( $event->ID );
$city = tribe_get_city( $event->ID );
$state = tribe_get_stateprovince($event->ID);
$country = tribe_get_country( $event->ID );
$zipcode = tribe_get_zip( $event->ID );
$fulladdress= concatenation of these variables..
Run Code Online (Sandbox Code Playgroud)

Riz*_*123 20

此解决方案应该适合您:

只需将所有变量放入一个数组并过滤掉所有空值array_filter(),然后implode()用逗号过滤它们,例如

$fulladdress = implode(",", array_filter([$street, $city, $state, $country, $zipcode])) ;
Run Code Online (Sandbox Code Playgroud)