array_pad()是PHP的内置函数,用于将固定时间的值填充到数组上。此函数将指定次数的元素插入数组的前面或后面。
用法:
array array_pad($input_array, $input_size, $values)
参数:该函数接受三个参数,所有这些参数都是必须提供的。
$input_array(强制性):指要在其上执行操作或需要向其添加元素的数组。
$total_size(强制性):指要返回的新数组的总大小。如果该值为正,则将元素添加到数组的末尾。
如果该值为负,则在数组的开头添加元素。
$values(必填):指将进行填充的值。仅当$total_size大于input_array的大小时,才会进行填充。
返回值:该函数返回填充为$total_size大小的数组的副本。如果$total_size的绝对值小于或等于数组的长度,则不进行填充。一次最多可以添加1048576个元素。
例子:
Input : array = ("one", "two", "three", "four", "five")
$total_size = 7 , $value = "six"
Output :
Array
(
[0] => one
[1] => two
[2] => three
[3] => four
[4] => five
[5] => six
[6] => six
)
Input : array = ("one", "two", "three", "four", "five")
$total_size = -7 , $value = "six"
Output :
Array
(
[0] => six
[1] => six
[2] => one
[3] => two
[4] => three
[5] => four
[6] => five
)
以下程序说明了array_pad()函数的工作方式:
$total_size为正数时,在数组末尾填充元素:
// PHP function to illustrate the use of array_pad()
function Padding($array, $string)
{
$result = array_pad($array, 7, $string);
return($result);
}
$array = array("one", "two", "three", "four", "five");
$string = "six";
print_r(Padding($array, $string));
?>
输出:
Array
(
[0] => one
[1] => two
[2] => three
[3] => four
[4] => five
[5] => six
[6] => six
)
$total_size为负数时,在数组开头填充元素:
// PHP function to illustrate the use of array_pad()
function Padding($array, $string)
{
$result = array_pad($array, -7, $string);
return($result);
}
$array = array("one", "two", "three", "four", "five");
$string = "six";
print_r(Padding($array, $string));
?>
输出:
Array
(
[0] => six
[1] => six
[2] => one
[3] => two
[4] => three
[5] => four
[6] => five
)