- PHP: array_fill() function
- PHP: Tips of the Day
- array_fill
- Parameters
- Return Values
- Errors/Exceptions
- Changelog
- Examples
- Notes
- See Also
- User Contributed Notes 7 notes
- array_fill
- Список параметров
- Возвращаемые значения
- Ошибки
- Список изменений
- Примеры
- Примечания
- Смотрите также
- The Ultimate Guide to PHP’s array_fill Function
- What is the array_fill Function in PHP?
- How to Use the array_fill Function in PHP
- Real-World Applications of the array_fill Function in PHP
- Initializing Arrays
- Creating Multidimensional Arrays
- Filling Arrays with Incremental Values
- Conclusion
PHP: array_fill() function
The array_fill() function is used to fill an array with values.
The function fills an array with num entries of the value of the array_values parameter, keys starting at the starting_index parameter.
array_fill(starting_index, num_of_elements, array_values )
Name | Description | Required / Optional | Type |
---|---|---|---|
starting_index | The first index of the returned array. Allows non-negative indexes only. | Required | Integer |
num_of_elements | Number of elements to insert. | Required | Integer |
array_values | Values to be used for filling. | Required | Mixed* |
*Mixed : Mixed indicates that a parameter may accept multiple (but not necessarily all) types.
Return value:
Value Type: Array
Array ([10] => Geography [11] => Geography [12] => Geography [13] => Geography [14] => Geography )
Pictorial Presentation:
Practice here online :
Previous:array_diff
Next: array_filter
Follow us on Facebook and Twitter for latest update.
PHP: Tips of the Day
stdClass is PHP’s generic empty class, kind of like Object in Java or object in Python (Edit: but not actually used as universal base class; thanks @Ciaran for pointing this out).
It is useful for anonymous objects, dynamic properties, etc.
An easy way to consider the StdClass is as an alternative to associative array. See this example below that shows how json_decode() allows to get an StdClass instance or an associative array. Also but not shown in this example, SoapClient::__soapCall returns an StdClass instance.
'; $stdInstance = json_decode($json); echo $stdInstance->foo . PHP_EOL; //"bar" echo $stdInstance->number . PHP_EOL; //42 //Example with associative array $array = json_decode($json, true); echo $array['foo'] . PHP_EOL; //"bar" echo $array['number'] . PHP_EOL; //42
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook
array_fill
Fills an array with count entries of the value of the value parameter, keys starting at the start_index parameter.
Parameters
The first index of the returned array.
If start_index is negative, the first index of the returned array will be start_index and the following indices will start from zero prior to PHP 8.0.0; as of PHP 8.0.0, negative keys are incremented normally (see example).
Number of elements to insert. Must be greater than or equal to zero, and less than or equal to 2147483647 .
Return Values
Errors/Exceptions
Throws a ValueError if count is out of range.
Changelog
Version | Description |
---|---|
8.0.0 | array_fill() now throws a ValueError if count is out of range; previously E_WARNING was raised, and the function returned false . |
Examples
Example #1 array_fill() example
The above example will output:
Array ( [5] => banana [6] => banana [7] => banana [8] => banana [9] => banana [10] => banana )
Example #2 array_fill() example with a negative start index
Output of the above example in PHP 7:
Array ( [-2] => pear [0] => pear [1] => pear [2] => pear )
Output of the above example in PHP 8:
Array ( [-2] => pear [-1] => pear [0] => pear [1] => pear )
Note that index -1 is not present prior to PHP 8.0.0.
Notes
See also the Arrays section of manual for a detailed explanation of negative keys.
See Also
- array_fill_keys() — Fill an array with values, specifying keys
- str_repeat() — Repeat a string
- range() — Create an array containing a range of elements
User Contributed Notes 7 notes
This is what I recently did to quickly create a two dimensional array (10×10), initialized to 0:
$a = array_fill ( 0 , 10 , array_fill ( 0 , 10 , 0 ));
?>
This should work for as many dimensions as you want, each time passing to array_fill() (as the 3rd argument) another array_fill() function.
If you need negative indices:
$b = array_fill (- 2 , 4 , ‘pear’ ); //this is not what we want
$c = array_fill_keys ( range (- 2 , 1 ), ‘pear’ ); //these are negative indices
print_r ( $b );
print_r ( $c );
?>
Here is result of the code above:
Array
(
[-2] => pear
[0] => pear
[1] => pear
[2] => pear
)
Array
(
[-2] => pear
[-1] => pear
[0] => pear
[1] => pear
)
Using objects with array_fill may cause unexpected results. Consider the following:
//fill an array with objects
$array = array_fill ( 0 , 2 , new Foo ());
//now we change the attribute of the object stored in index 0
//this actually changes the attribute for EACH object in the ENTIRE array
$array [ 0 ]-> bar = «apple» ;
var_dump ( $array );
/*
array(2) [0]=>
object(Foo)#1 (1) [«bar»]=>
string(5) «apple»
>
[1]=>
object(Foo)#1 (1) [«bar»]=>
string(5) «apple»
>
>
*/
?>
Objects are filled in the array BY REFERENCE. They are not copied for each element in the array.
As of PHP 8.0 the example code
$b = array_fill (- 2 , 4 , ‘pear’ );
print_r ( $b );
?>
now returns
I made this function named «array_getMax» that returns te maximum value and index, from array:
//using array_search_all by helenadeus at gmail dot com
foreach ( $haystack as $k => $v )
$array [] = $k ;
>
>
return ( $array );
function array_getMax ( $array )
$conteo = array_count_values ( $array );
//$antValue=null;
$maxValue = null ;
$keyValue = null ;
foreach( $array as $key => $value ) <
if( $maxValue == null ) <
$maxValue = $value ;
$keyValue = $key ;
break;
>
>
$resultSearch = array_search_all ( $maxValue , $array );
return array_fill_keys ( $resultSearch , $maxValue );
//example
$arreglo =array( ‘e1’ => 99 , ‘e2′ => ’99’ , ‘e3’ => 1 , ‘e4’ => 1 , ‘e5’ => 98 );
var_dump ( array_getMax ( $arreglo ));
Fill missing keys in a (numerically-indexed) array with a default value
function fill_missing_keys ( $array , $default = null , $atleast = 0 )
return $array + array_fill ( 0 , max ( $atleast , max ( array_keys ( $array ))), $default );
>
array_fill() cannot be used to setup only missing keys in an array. This may be necessary for example before using implode() on a sparse filled array.
The solution is to use this function:
function array_setkeys (& $array , $fill = NULL ) <
$indexmax = — 1 ;
for ( end ( $array ); $key = key ( $array ); prev ( $array )) <
if ( $key > $indexmax )
$indexmax = $key ;
>
for ( $i = 0 ; $i if (!isset( $array [ $i ]))
$array [ $i ] = $fill ;
>
ksort ( $array );
>
?>
This is usefull in some situations where you don’t know which key index was filled and you want to preserve the association between a positioned field in an imploded array and the key index when exploding it.
- Array Functions
- array_change_key_case
- array_chunk
- array_column
- array_combine
- array_count_values
- array_diff_assoc
- array_diff_key
- array_diff_uassoc
- array_diff_ukey
- array_diff
- array_fill_keys
- array_fill
- array_filter
- array_flip
- array_intersect_assoc
- array_intersect_key
- array_intersect_uassoc
- array_intersect_ukey
- array_intersect
- array_is_list
- array_key_exists
- array_key_first
- array_key_last
- array_keys
- array_map
- array_merge_recursive
- array_merge
- array_multisort
- array_pad
- array_pop
- array_product
- array_push
- array_rand
- array_reduce
- array_replace_recursive
- array_replace
- array_reverse
- array_search
- array_shift
- array_slice
- array_splice
- array_sum
- array_udiff_assoc
- array_udiff_uassoc
- array_udiff
- array_uintersect_assoc
- array_uintersect_uassoc
- array_uintersect
- array_unique
- array_unshift
- array_values
- array_walk_recursive
- array_walk
- array
- arsort
- asort
- compact
- count
- current
- end
- extract
- in_array
- key_exists
- key
- krsort
- ksort
- list
- natcasesort
- natsort
- next
- pos
- prev
- range
- reset
- rsort
- shuffle
- sizeof
- sort
- uasort
- uksort
- usort
- each
array_fill
Заполняет массив num элементами со значением value , начиная с ключа start_index .
Список параметров
Первый индекс возвращаемого массива.
Если start_index отрицателен, первым индексом возвращаемого массива будет start_index , а последующие индексы будут начинаться с нуля (смотрите пример).
Количество вставляемых элементов. Их должно быть больше или равно нулю.
Возвращаемые значения
Возвращает заполненный массив
Ошибки
Вызывает предупреждение E_WARNING в случае, если параметр num меньше нуля.
Список изменений
Версия Описание 5.6.0 num теперь может быть равен нулю. До этого num должен был быть больше нуля. Примеры
Пример #1 Пример использования array_fill()
$a = array_fill ( 5 , 6 , ‘banana’ );
$b = array_fill (- 2 , 4 , ‘pear’ );
print_r ( $a );
print_r ( $b );
?>?phpРезультат выполнения данного примера:
Array ( [5] => banana [6] => banana [7] => banana [8] => banana [9] => banana [10] => banana ) Array ( [-2] => pear [0] => pear [1] => pear [2] => pear )
Примечания
Смотрите также подробное описание отрицательных ключей в разделе Массивы.
Смотрите также
- array_fill_keys() — Создает массив и заполняет его значениями, с определенными ключами
- str_repeat() — Возвращает повторяющуюся строку
- range() — Создает массив, содержащий диапазон элементов
The Ultimate Guide to PHP’s array_fill Function
The array_fill function in PHP is a powerful tool for creating arrays filled with values of your choice. In this guide, we’ll take a deep dive into how to use this function and how it can be applied in real-world scenarios.
What is the array_fill Function in PHP?
The array_fill function is a built-in PHP function that takes three arguments: the start index, the number of elements, and the value to fill the array with. The function returns an array with the specified number of elements, each with the specified value.
How to Use the array_fill Function in PHP
Using the array_fill function is straightforward. Simply specify the start index, number of elements, and the value you want to fill the array with, and the function will return an array with the specified values.
Here’s an example of how to use the array_fill function to create an array of 10 elements, starting at index 0, filled with the value «PHP»:
$array = array_fill(0, 10, "PHP"); print_r($array); ?>
The resulting array will look like this:
Array ( [0] => PHP [1] => PHP [2] => PHP [3] => PHP [4] => PHP [5] => PHP [6] => PHP [7] => PHP [8] => PHP [9] => PHP )
Real-World Applications of the array_fill Function in PHP
The array_fill function can be used in a variety of real-world scenarios. Here are some examples:
Initializing Arrays
One of the most common uses for the array_fill function is to initialize arrays with default values. For example, you could use the function to create an array of default values for a form field.
Creating Multidimensional Arrays
The array_fill function can also be used to create multidimensional arrays. For example, you could use the function to create a 2D array filled with zeros:
$array = array_fill(0, 10, array_fill(0, 10, 0)); print_r($array); ?>
This will create a 10×10 array filled with zeros.
Filling Arrays with Incremental Values
The array_fill function can also be used to fill an array with incremental values. For example, you could use the function to create an array of numbers from 1 to 10:
$array = array_fill(1, 10, range(1, 10)); print_r($array); ?>
This will create an array with 10 elements, starting at index 1, filled with the numbers 1 to 10.
Conclusion
The array_fill function in PHP is a powerful tool for creating arrays filled with values of your choice. Whether you’re initializing arrays, creating multidimensional arrays, or filling arrays with incremental values, this function is a great solution. We hope this guide has helped you learn how to use the array_fill function in PHP.