如何在php中使用null效果连接各种字符串[重复]

wljmcqd8  于 12个月前  发布在  PHP
关注(0)|答案(4)|浏览(66)

此问题已在此处有答案

PHP array and implode with blank/null values(2个答案)
去年就关门了。
我有四个PHP变量,比如:$abc, $bcd, $dsf, $gkg。现在我想用逗号将它们连接起来。
产出:

abc,bcd,dsf,gkg

现在如果任何变量没有返回任何值。那么输出是这样的:

abc,,dsf,gkg

那么,如果任何变量的值为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..
isr3a4wc

isr3a4wc1#

此解决方案应该适合您:
只需将所有变量放入一个数组中,然后用array_filter()过滤掉所有空值,然后用逗号implode()它们,例如。

$fulladdress = implode(",", array_filter([$street, $city, $state, $country, $zipcode])) ;
vktxenjb

vktxenjb2#

array_filter可用于从提供的数组中筛选出FALSE、空或Null字符串。
点击此处查看:http://php.net/manual/en/function.array-filter.php

<?php

    $entry = array(
         0 => 'foo',
         1 => false,
         2 => -1,
         3 => null,
         4 => ''
    );

    print_r(array_filter($entry));
?>

上面的代码将输出:

Array
(
    [0] => foo
    [2] => -1
)

现在使用','对结果数组进行内爆,这样你就得到了一个字符串,其中所有非空元素都用,
以下是我在代码中使用的:

$Matter_Client_Address_City_ST_Zip =      
    implode(",",array_filter([$Matter_Client_City, 
    $Matter_Client_State,$Matter_Client_Zip]));

上述代码将仅输出由逗号(,)分隔的非空字段,因此如果city为空,则将输出CA,92620

atmip9wb

atmip9wb3#

这段代码没有优化,但它可以工作:

<?php
    $abc = "abc";
    $bcd = null;
    $cde = "cde";


/**
 * concatenate some values
 * @param $values an array witch contains all values to concatenate
 */
function concat( $values = array() )
{
    //Look over all values
    for ($i = 0; $i < count($values); $i++) {
        //If current value is not null or empty, display it
        if ( !empty($values[$i]) )
            echo $values[$i];
        //If current value is not null AND if it is not the last value
        if ( !empty($values[$i]) && $i < count($values) -1 )
            echo ', ';
    }
}
concat(array($abc, $bcd, $cde));
qrjkbowd

qrjkbowd4#

可以帮助:

function concat_ws(){
    $ar=func_get_args();
    return implode(array_shift($ar), array_filter($ar)) ;
}
echo concat_ws(" - ", "hello", "", null, "world");

返回:hello - world

相关问题