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

黄舟
Release: 2023-03-17 08:08:01
Original
1588 people have browsed it

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"));
?>
Copy after login

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)
Copy after login
ParametersDescription
array Required. Specifies an array.
sizeRequired. Specifies the number of array elements returned from the function.
valueRequired. 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"));
?>
Copy after login

Example:

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

Output:

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

Example 2:

With negative size Parameter:

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

Output:

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

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template