Blog de programación, errores, soluciones

Chose Language:
comments
Author: Admin/Publisher |finished | checked

PHP array_pad function

The PHP function array_pad takes an array and extends it to a specific length by filling it with a specified value.

Description / Descripción
array_pad(array $array, int $length, mixed $value): array
Sintaxis / Sintax
$parray = array_pad(array("Pepe","Monica","Joel"),10,"Juan");

If the given length in $length is positive, the array will be padded to the right. In case the passed length is negative, the padding will occur to the left.

If the value of $length is less than the length of the array, the array will not be padded.

It is possible to add up to 1048576 elements at a time.

Parameters

$array – the array to be padded.

$length – the new length of the array.

$value – the value with which it will be padded.

Returns

array – depending on the value of the length and the value.

array – if the length of the array is greater than $length, the input array will be returned.

PHP array_pad examples

We will provide some examples so you can see how the array_pad function fills the array.

Fills to the right of the array
$my_array = ["gato","perro","raton","pez"];
$parray = array_pad($my_array,10,"caballo");
print_r($parray);
Array
(
    [0] => gato
    [1] => perro
    [2] => raton
    [3] => pez
    [4] => caballo
    [5] => caballo
    [6] => caballo
    [7] => caballo
    [8] => caballo
    [9] => caballo
)

The following example is identical to the previous one, except now $length will be negative

Fills to the left of the array
$my_array = ["gato","perro","raton","pez"];
$parray = array_pad($my_array,-10,"caballo");
print_r($parray);
Array
(
    [0] => caballo
    [1] => caballo
    [2] => caballo
    [3] => caballo
    [4] => caballo
    [5] => caballo
    [6] => gato
    [7] => perro
    [8] => raton
    [9] => pez
)
Category: en-php
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category

Comments