PHP 数组操作全解析:从基础到高级技巧
1. 数组元素合并成字符串
若要将字符数组合并成字符串,可使用 implode()
函数,示例如下:
$array = ['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'];
$option1 = implode($array);
$option2 = implode('', $array);
echo 'The two are ' . ($option1 === $option2 ? 'identical' : 'different');
// 输出:The two are identical
由于能明确指定分隔符, implode()
功能强大。若数组是单词列表,可如下操作生成逗号分隔的列表:
$fruit = ['apple', 'orange', 'pear', 'peach'];
echo implode(', ', $fruit);
// 输出:apple, orange, pear, peach
2. 反转数组
若要反转数组元素顺序,可使用 array_reverse()
函数:
$array = ['five', 'four', 'three', 'two', 'one', 'zer