PHP implode() 是一個字符串函數,它將數組元素連接成一個字符串。它是一個二進製安全函數。在 implode() 函數中,參數可以按任意順序傳遞。
implode() 函數的工作原理與 join() 函數相同,並返回從數組元素創建的字符串。本質上,這個函數將數組的所有元素連接到一個字符串中。
用法
implode() 函數有兩種可用的語法,如下所示:
implode (string $glue, array $pieces)
或者
implode (array $pieces)
通過 $glue 字符串參數連接數組元素。
參數
implode() 函數中可以傳遞兩個參數,一個是必須的,另一個是可選的。這些參數如下:
$glue(可選):
它是一個可選的字符串類型的參數。它包含連接數組元素並形成字符串的值。本質上, $glue 用於連接字符串。
$pieces (強製):
此參數包含要內爆的字符串數組。數組元素必須傳入 implode() 函數以連接成一個字符串。
返回值
implode() 函數返回由數組元素組成的字符串。字符串將按照與傳入數組的元素相同的順序形成。該函數的返回類型是字符串。
變化
在 PHP 7.4.0 版本之後,不推薦在 $pieces 參數之後傳遞 $glue 參數。
例子
範例1:
在下麵的示例中,數組元素使用 implode() 函數與 + 運算符連接。
<?php
echo "Before using 'implode()' function:<br>";
echo "array('Welcome', 'to', 'PHP', 'tutorial') <br> <br>";
//store array element in a variable
$arr = array('Welcome', 'to', 'PHP', 'tutorial');
//join array elements in a string by + operator
echo "After using 'implode()' function:<br>";
echo implode("+",$arr);
?>
輸出:
Before using 'implode()' function: array('Welcome', 'to', 'PHP', 'tutorial') After using 'implode()' function: Welcome+to+PHP+tutorial
範例2:
<?php
$input_arr = array ('Noida', 'Delhi', 'Gurugram');
//join with comma and space separator
$comma_separation = implode (", ", $input_arr);
echo $comma_separation;
echo "</br>";
//join without separator
print_r (implode ($input_arr));
?>
輸出:
Noida, Delhi, Gurugram NoidaDelhiGurugram
範例3:
在下麵的示例中,兩個數組使用 implode() 函數連接在一起。
<?php
$input_arr1 = array ('Hello', 'everyone!');
$input_arr2 = array ('One' => 'Welcome', 'Two' => 'to', 'Three' => 'Javatpoint');
//join both array elements
echo implode(' ', $input_arr1), ' / ', implode(' ', $input_arr2);
?>
輸出:
Hello everyone! / Welcome to Javatpoint
相關用法
- PHP string rtrim()用法及代碼示例
- PHP string printf()用法及代碼示例
- PHP string ord()用法及代碼示例
- PHP string join()用法及代碼示例
- PHP string sha1()用法及代碼示例
- PHP string setlocale()用法及代碼示例
- PHP string sha1_file()用法及代碼示例
- PHP string md5()用法及代碼示例
- PHP string ltrim()用法及代碼示例
- PHP string str_repeat()用法及代碼示例
- PHP string lcfirst()用法及代碼示例
- PHP string str_shuffle()用法及代碼示例
- PHP string similar_text()用法及代碼示例
- PHP string crypt()用法及代碼示例
- PHP string str_ireplace()用法及代碼示例
- PHP string str_split()用法及代碼示例
- PHP string strcoll()用法及代碼示例
- PHP string str_rot13()用法及代碼示例
- PHP string str_pad()用法及代碼示例
注:本文由純淨天空篩選整理自 PHP string Implode() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。