如何在 PHP 中从一个数组创建一个逗号分隔列表?
要在 PHP 中从一个数组创建一个逗号分隔列表,代码如下−
示例
<?php $arr = array( " John ", "Jacob ", " Tom ", " Tim "); echo "Array with leading and trailing whitespaces...
"; foreach( $arr as $value ) { echo "Value = $value
"; } echo "
Comma separated list...
"; print_r(implode(', ', $arr)); $result = array_map('trim', $arr); echo "
Updated Array...
"; foreach( $result as $value ) { echo "Value = $value
"; } ?>
输出
这将产生以下输出−
Array with leading and trailing whitespaces... Value = John Value = Jacob Value = Tom Value = Tim Comma separated list... John , Jacob , Tom , Tim Updated Array... Value = John Value = Jacob Value = Tom Value = Tim
示例
我们现在来看另一个示例 −
<?php $arr = array(100, 200, 300, 400, 500); echo "Comma separated list...
"; print_r(implode(', ', $arr)); ?>
输出
这将产生以下输出−
Comma separated list... 100, 200, 300, 400, 500
广告