PHP function introduction—array_pad(): Fill the array to the specified length with the specified value
In PHP, there are many commonly used array functions that can help us quickly process and operate arrays. One of the very useful functions is the array_pad() function. This function fills an array to a specified length with a specified value.
The syntax of the array_pad() function is as follows:
array_pad(array $array, int $size, mixed $value): array
Parameter description:
Next, we demonstrate the usage of the array_pad() function through a simple code example.
// 定义一个数组 $numbers = ['1', '2', '3']; // 将数组填充到指定长度 $paddedArray = array_pad($numbers, 5, '0'); // 输出结果 print_r($paddedArray);
Run the above code, we will get the following output:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 0 [4] => 0 )
As can be seen from the output, the original array $numbers is filled to a length of 5, and the value is ' 0' is padded. In the new filled array $paddedArray, the elements of the original array remain at their original positions, while the newly filled elements are added to the end of the array.
In addition to padding the array to the specified length, the array_pad() function can also accept negative length parameters. When the length parameter is negative, the array will be filled based on the original value. That is, if the specified length is less than the length of the original array, the function will delete the elements at the end of the array.
Let’s look at the code example again:
// 定义一个数组 $numbers = ['1', '2', '3']; // 将数组在原来长度基础上进行填充 $paddedArray = array_pad($numbers, -5, ''); // 输出结果 print_r($paddedArray);
Run the above code, we will get the following output:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => [4] => )
From the output results, the original array $numbers is in the original Padded based on the length, empty string elements are added to the new filled array $paddedArray, and the number of elements is consistent with the padded length.
To summarize, the array_pad() function is a very practical array function in PHP. It fills an array to a specified length with a specified value. Whether it is to pad the array to a longer length or to fill it at the original length, the array_pad() function can meet our needs. By using this function flexibly, we can handle and manipulate arrays more efficiently.
The above is the detailed content of PHP function introduction—array_pad(): fills the array to the specified length with the specified value. For more information, please follow other related articles on the PHP Chinese website!