给定一个数组,我们必须使用该数组创建一个逗号分隔的字符串,而不使用库函数。
示例
Input: array("Google","Bing","Yahoo!","DuckDuckGo") Output: comma delimited string: "Google, Bing, Yahoo!, DuckDuckGo"
<?php 即可反转字符串 //使用库函数 //函数定义 //它接受一个数组并返回逗号分隔的字符串 function create_string($arr){ //变量以存储字符串 $str = ''; for($i = 0; $i < count($arr); $i++){ $str .= $arr[$i]; if($i < (count($arr) -1)){ $str .= ", "; } } //返回结果,即逗号分隔的字符串 return $str; } //主代码,即函数调用 $arr = array("New Delhi","Mumbai","Chennai","Banglore"); $result = create_string($arr); echo "array is: ". "<br/>"; print_r($arr); echo "comma delimited string: " .$result ."<br/>"; $arr = array("Google","Bing","Yahoo!","DuckDuckGo"); $result = create_string($arr); echo "array is: ". "<br/>"; print_r($arr); echo "comma delimited string: " .$result ."<br/>"; ?>
输出结果
array is: Array ( [0] => New Delhi [1] => Mumbai [2] => Chennai [3] => Banglore ) comma delimited string: New Delhi, Mumbai, Chennai, Banglore array is: Array ( [0] => Google [1] => Bing [2] => Yahoo! [3] => DuckDuckGo ) comma delimited string: Google, Bing, Yahoo!, DuckDuckGo
说明:
每当打印数组中的一个值时,我们使用for循环读取数组并将其存储到以(,)分隔的字符串中。这一直持续到我们到达最后一个字符串为止,以避免在列表末尾打印另一个逗号。