Home  >  Article  >  Backend Development  >  How to fill a value into an array with a specified length in PHP

How to fill a value into an array with a specified length in PHP

PHPz
PHPzforward
2024-03-19 11:10:26449browse

php Xiaobian Yuzai will introduce to you how to use PHP to fill a value of a specified length into an array. In PHP, you can use the array_pad() function to achieve this functionality. This function accepts three parameters: the original array, the final array length, and the values ​​to be filled. Through this function, you can easily fill the value of the specified length into the array to achieve the effect you want. Next, let’s take a look at the specific implementation method!

PHP uses the array_pad() function to fill the array

The

array_pad() function in php is used to fill a given array to the specified length with the specified padding value. Its syntax is as follows:

array_pad(array $array, int $pad_length, mixed $pad_value, int $pad_type = STR_PAD_RIGHT) : array

parameter:

  • $array: The array to be filled.
  • $pad_length: The target length to be padded. If the array length is greater than this value, no padding is performed.
  • $pad_value: Value added to the array to fill in the gaps.
  • $pad_type (optional): Specify the padding type. The following are valid options:
    • STR_PAD_RIGHT: Pad values ​​at the end of the array (default).
    • STR_PAD_LEFT: Fill the value at the beginning of the array.
    • STR_PAD_BOTH: Fill in values ​​at both ends of the array.

return value:

Returns a new array containing filled elements. The original array will not be modified.

Example:

$array = ["foo", "bar", "baz"];

// Fill the array to 5 elements using the default fill type (STR_PAD_RIGHT) with the value "qux"
$padded_array = array_pad($array, 5, "qux");

print_r($padded_array); // Output: ["foo", "bar", "baz", "qux", "qux"]

// Use STR_PAD_LEFT to fill the array to 7 elements with the value "pre"
$padded_array = array_pad($array, 7, "pre", STR_PAD_LEFT);

print_r($padded_array); // Output: ["pre", "pre", "foo", "bar", "baz", "qux", "qux"]

// Use STR_PAD_BOTH to fill the array to 6 elements with the value "xyz"
$padded_array = array_pad($array, 6, "xyz", STR_PAD_BOTH);

print_r($padded_array); // Output: ["xyz", "foo", "bar", "baz", "xyz", "xyz"]

Notice:

  • If $pad_length is less than the length of the original array, the array will not be filled.
  • If $pad_length is less than or equal to 0, an InvalidArgumentExcept<strong class="keylink">io</strong>n exception will be thrown.
  • The fill value can be of any data type.

The above is the detailed content of How to fill a value into an array with a specified length in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:lsjlt.com. If there is any infringement, please contact admin@php.cn delete