Php - 使用join()时可以忽略/跳过空字符串

Gow*_*ire 1 php arrays join

我有一个PHP脚本,它将基于几个子串生成一个连接字符串.

作为一个例子,我在下面提供了一些示例代码,它采用了第一个,中间名和最后一个名称的数组,并在join函数中添加了一个换行符.

第二个数组包含一个空字符串(中间名),我想在连接期间忽略它.

我想找到一个解决方案,我可以忽略join()函数中的空字符串.

它可以用一些巧妙的"技巧"完成,还是我必须先从空字符串中过滤数组?

// The array is designed as [firstname, middlename, lastname]
$names1 = array("John", "William", "Smith");
$names2 = array("Adam", "", "Johnson");

echo join("<br>", $names1);
echo "<br>";
echo join("<br>", $names2);

// Result:
/*
John
William
Smith

Adam
             <-- Can this empty line be ignored by some "trick"? :)
Johnson
Run Code Online (Sandbox Code Playgroud)

NB.我在实际情况中的数组包含的条件应由"AND"关键字分隔.我想避免结果为"condition1 AND AND condition3"

emi*_*mix 5

只需过滤掉空数组项:

echo join('<br>', array_filter($names2, 'strlen'));
Run Code Online (Sandbox Code Playgroud)

  • 请注意,“0”也将以这种方式过滤。也许可以用 `array_filter(..., 'strlen')` 来代替。 (2认同)