Home >Backend Development >PHP Tutorial >php function array_pad() that inserts a specified number of elements with a specified value into an array

php function array_pad() that inserts a specified number of elements with a specified value into an array

黄舟
黄舟Original
2017-11-08 10:26:281655browse

Example

Returns 5 elements and inserts the "blue" value into a new element of the array:

<?php
$a=array("red","green");
print_r(array_pad($a,5,"blue"));
?>

Definition and usage

array_pad() FunctionInserts the specified number of elements with the specified value into the array.

Tip: If you set the size parameter to a negative number, this function inserts the new element before the original array (see example below).

Note : If the size parameter is smaller than the length of the original array, this function will not delete any elements.

Syntax

array_pad(array,size,value)
Parameters Description
array Required. Specifies an array.
size Required. Specifies the number of array elements returned from the function.
value Required. Specifies the value of the new element in the array returned from the function.

Technical details

Return value: Returns an array with the new element.
PHP version: 4+
##More examples

Example 1

Use size parameters with negative values:

<?php
$a=array("red","green");
print_r(array_pad($a,-5,"blue"));
?>

Example:

<?php  
$a=array("Dog","Cat");  
print_r(array_pad($a,5,0));  
?>

Output:

Array ( [0] => Dog [1] => Cat [2] => 0 [3] => 0 [4] => 0 )

Example 2:

With negative size Parameter:

<?php  
$a=array("Dog","Cat");  
print_r(array_pad($a,-5,0));  
?>

Output:

Array ( [0] => 0 [1] => 0 [2] => 0 [3] => Dog [4] => Cat )

The above is the detailed content of php function array_pad() that inserts a specified number of elements with a specified value into an array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn