array_pad

(PHP 4, PHP 5)

array_padДополнить размер массива определенным значением до заданной величины

Описание

array array_pad ( array $input , int $pad_size , mixed $pad_value )

Функция array_pad() возвращает копию массива input, дополненного до размера pad_size элементами со значением pad_value. Если параметр pad_size положителен, то массив увеличивается вправо, если отрицателен - влево. Если абсолютное значение параметра pad_size меньше или равно размеру массива input, функция не производит никаких операций. За один раз возможно добавить максимум 1048576 элементов.

Список параметров

input

Исходный массив, к которому дополняются элементы.

pad_size

Новый размер массива.

pad_value

Дополняемое значение, если длина массива input меньше pad_size.

Возвращаемые значения

Возвращает копию input, дополненного до размера указанного pad_size значением pad_value. Если параметр pad_size положителен, то массив дополняется вправо, если он отрицателен - влево. Если абсолютное значение pad_size меньше либо равно длине input, то дополнение не происходит.

Примеры

Пример #1 Пример использования array_pad()

<?php
$input 
= array(12109);

$result array_pad($input50);
// результат: array(12, 10, 9, 0, 0)

$result array_pad($input, -7, -1);
// результат: array(-1, -1, -1, -1, 12, 10, 9)

$result array_pad($input2"noop");
// операция не произведена

Смотрите также

  • array_fill() - Заполняет массив значениями
  • range() - Создает массив, содержащий диапазон элементов

Коментарии

Автор:
to the previous commenter -- if you read the manual entry, you'd see that a negative pad_size will put the pad values at the front of the array.
2002-07-19 19:20:08
http://php5.kiev.ua/manual/ru/function.array-pad.html
yes that is true. But, if the index of the array is 2=two, 3=three

and i want 4 more keys to be filled. But, not just filled anywhere, but i want to maintain the key index.

so, i would like to have 0=FILLED, 1=FILLED ... 4=FILLED, 5=FILLED

now i got 4 more keys padded with my string.

We can do this "if" we know the missing keys, but if we dont, then it would be nice for array_pad() or perhaps some new function to do this?

obviously we can achive this by looping through the array using array_key_exists(), and if you dont find the key, simply create + fill it.
regards,
Daarius...
2002-07-23 10:36:33
http://php5.kiev.ua/manual/ru/function.array-pad.html
OR you could do this 

<?php
$myArr 
= array(=> 'three'=> 'four');

$newArr array_pad(array(), 4'FILLED');
$newArr =$myArr+$newArr;
?>

This gives your desired result BUT the ordering is a little wierd, because of the order they were added. Indexes are okay though and that is what you wanted.

print_r($newArr) outputs
Array ( [2] => three [3] => four [0] => FILLED [1] => FILLED )

hope this helps
2002-09-19 12:39:38
http://php5.kiev.ua/manual/ru/function.array-pad.html
To daarius - you mean you have...

[2]=>"two"
[3]=>"three"

and you want...

[0]=>"FILLED"
[1]=>"FILLED"
[2]=>"two"
[3]=>"three"
[4]=>"FILLED"
[5]=>"FILLED"

If so, then the following code...

<?php
$array 
= array(=> "two"=> "three");
$array array_pad($arraycount($array)+2"FILLED");
$num = -(count($array)+2);
$array array_pad($array$num"FILLED");
print_r($array);
?>

will return:
Array ( [0] => FILLED [1] => FILLED [2] => two [3] => three [4] => FILLED [5] => FILLED )
The ordering should be okay,...
2003-03-23 19:06:54
http://php5.kiev.ua/manual/ru/function.array-pad.html
little older, a little wiser.

ksort() will order the array back into its normal order again
so:

<?php
$myArr 
= array(=> 'two'=> 'four');

$newArr array_pad(array(), 6'FILLED');
$newArr =$myArr+$newArr;
ksort($newArr);
?>

Will give : 
Array ( [0] => FILLED [1] => FILLED [2] => two [3] => FILLED [4] => four [5] => FILLED )
2004-01-16 10:02:44
http://php5.kiev.ua/manual/ru/function.array-pad.html
Автор:
One way to initialize a 20x20 multidimensional array. 

<?php
$a 
= array();
$b = array();
$b array_pad($b,20,0);
$a array_pad($a,20,$b);
?>
2004-02-28 23:00:40
http://php5.kiev.ua/manual/ru/function.array-pad.html
Easy way to get an array contains 5 random numbers from 0 to 9:

$rand_arr = array_rand( array_pad( array(), 10, 1 ), 5 );
2004-10-22 02:48:21
http://php5.kiev.ua/manual/ru/function.array-pad.html
A simple example for array_pad()

the syntax is as follows: array_pad(array(), (+/-)int, value)

where "array" is the array to which the value is to be added,

"(+/-) int" is a value that decides the length of the array(it should be greater than the length of the array.
if its a negative number then the value will be added at the left of the array else it will be added to the right.

"values" denotes the value to be added to the array

lets try an example:

<?php

$digits 
= array();
$digits[0] = 1;
$digits[1] = 2;
$digits[2] = 3;
$arraypad array_pad($digits, -4"0");
print_r($arraypad);

?>

output:

Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 )
2007-01-08 04:15:19
http://php5.kiev.ua/manual/ru/function.array-pad.html
Автор:
Beware, if you try to pad an associative array using numeric keys, your keys will be re-numbered.

<?php
$a 
= array('size'=>'large''number'=>20'color'=>'red');
print_r($a);
print_r(array_pad($a5'foo'));

// use timestamps as keys
$b = array(1229600459=>'large'1229604787=>201229609459=>'red');
print_r($b);
print_r(array_pad($b5'foo'));
?>

yields this:
------------------
Array
(
    [size] => large
    [number] => 20
    [color] => red
)
Array
(
    [size] => large
    [number] => 20
    [color] => red
    [0] => foo
    [1] => foo
)
Array
(
    [1229600459] => large
    [1229604787] => 20
    [1229609459] => red
)
Array
(
    [0] => large
    [1] => 20
    [2] => red
    [3] => foo
    [4] => foo
)
2008-12-18 11:23:35
http://php5.kiev.ua/manual/ru/function.array-pad.html
Just an info about the value of "$pad_size" , 

If we set the value of "$pad_size" from -3 to 3,

It will produce the output like:

<?php
$result 
array_pad($input, -3"noop");
//result is array(12, 10, 9)

$result array_pad($input3"noop");
//result is array(12, 10, 9)
?>

means array will remain the same.
2011-01-12 02:53:01
http://php5.kiev.ua/manual/ru/function.array-pad.html
// insert element to array
function array_insert(&$arr, $pos, $new_el=null) {
    $arraypad = array_pad($arr, count($arr)+1, 0);
    for ($i=count($arr)-1; $i>=$pos; $i--) {
        $arr[$i+1] = $arr[$i];
        if ($i == $pos) {
            $arr[$i] = $new_el;
        }
    }
}

$digits = array();
$digits[0] = 0;
$digits[1] = 1;
$digits[2] = 2;
$digits[3] = 3;
$digits[4] = 4;
$digits[5] = 5;
echo "was: "; var_dump($digits);

array_insert($digits, 3, 100);
echo "new: "; var_dump($digits);
2013-07-06 13:58:06
http://php5.kiev.ua/manual/ru/function.array-pad.html

    Поддержать сайт на родительском проекте КГБ