array_fill
Заполняет массив num элементами со значением value , начиная с ключа start_index .
Список параметров
Первый индекс возвращаемого массива.
Если start_index отрицателен, первым индексом возвращаемого массива будет start_index , а последующие индексы будут начинаться с нуля (смотрите пример).
Количество вставляемых элементов. Их должно быть больше или равно нулю.
Значение для заполнения
Возвращаемые значения
Возвращает заполненный массив
Ошибки
Вызывает предупреждение E_WARNING в случае, если параметр num меньше нуля.
Список изменений
| Версия | Описание |
|---|---|
| 5.6.0 | num теперь может быть равен нулю. До этого num должен был быть больше нуля. |
Примеры
Пример #1 Пример использования array_fill()
Результат выполнения данного примера:
Примечания
Смотрите также подробное описание отрицательных ключей в разделе Массивы.
array_fill
Заполняет массив count элементами со значением value , начиная с ключа start_index .
Список параметров
Первый индекс возвращаемого массива.
Если start_index отрицательный, первым индексом возвращаемого массива будет start_index , а последующие индексы будут начинаться с нуля до PHP 8.0.0; начиная с PHP 8.0.0, отрицательные ключи увеличиваются нормально (смотрите пример).
Количество добавляемых элементов. Должно быть больше или равно нулю и меньше или равно 2147483647 .
Значение для заполнения.
Возвращаемые значения
Возвращает заполненный массив.
Ошибки
Выбрасывает исключение ValueError в случае, если параметр count выходит за пределы диапазона.
Список изменений
| Версия | Описание |
|---|---|
| 8.0.0 | Функция array_fill() теперь выбрасывает исключение ValueError , если параметр count выходит за пределы диапазона; ранее выдавалась ошибка уровня E_WARNING , а функция возвращала значение false . |
Примеры
Пример #1 Пример использования array_fill()
Результат выполнения данного примера:
Пример #2 Пример использования array_fill() с отрицательным начальным индексом
Результат выполнения данного примера в PHP 7:
Результат выполнения данного примера в PHP 8:
Обратите внимание, что индекс -1 отсутствует до PHP 8.0.0.
Примечания
Смотрите также подробное описание отрицательных ключей в разделе Массивы.
Смотрите также
- array_fill_keys() — Создаёт массив и заполняет его значениями с определёнными ключами
- str_repeat() — Возвращает повторяющуюся строку
- range() — Создаёт массив, содержащий диапазон элементов
User Contributed Notes 7 notes
This is what I recently did to quickly create a two dimensional array (10×10), initialized to 0:
<?php
$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.
Using objects with array_fill may cause unexpected results. Consider the following:
<?php
class Foo <
public $bar = «banana» ;
>
//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
<?php
$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:
<?php
//using array_search_all by helenadeus at gmail dot com
foreach ( $haystack as $k => $v ) <
if( $haystack [ $k ]== $needle )<
$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:
<?php
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 <= $indexmax ; $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.
Arrays in PHP
Arrays are a strong data-handling tool in PHP. Arrays are a type of data structure that enables programmers to store and manipulate several values in a single variable. They are incredibly adaptable and may be utilized in a wide range of applications, from basic lists to complicated data structures. We will cover all you need to know to master dealing with PHP arrays in this comprehensive guide.
Understanding the Basics of PHP Arrays
There are two main types of arrays in PHP: indexed and associative.
Indexed Arrays
Indexed arrays are made by assigning many values to a single variable, each with its own integer index. As an example:
In this example, “apple” has the index 0, “banana” has the index 1, and “orange” has the index 2. These values may be accessed by using the array’s index, as seen below:
Associative Arrays
In contrast, associative arrays are built by assigning keys (strings or numbers) to values. As an example:
In this example, “name” is set to “John Smith,” “age” is set to “30,” and “address” is set to “123 Main St.”. These values may be accessed by using the array’s keys as follows:
Creating Arrays
There are several ways to create arrays in PHP, including:
- Using the array() function
- Using the square brackets []
- Using the range() function
Using the array() Function
In PHP, the array() method is the most often used technique to generate an array. As an example:
Using Square Brackets
You can also create an array using square brackets [] in PHP 5.4 and later versions. For example:
Using the range() Function
The range() function creates an array of numbers within a specified range. For example:
This creates an array of numbers from 1 to 10.
Accessing Array Elements
You can access the elements of an array using the index or key of the element. For example:
Modifying Array Elements
You can modify the elements of an array by assigning a new value to the index or key of the element. For example:
In this example, the value at index 0 of the $fruits array is changed from “apple” to “mango”.
Similarly, for associative arrays:
The value of the key “name” in the $person array is changed from “John Smith” to “Jane Doe” in this example.
Advanced Array Manipulation
After you’ve mastered the fundamentals of arrays, you may go on to more complex array manipulation techniques.
Sorting Arrays
PHP has a number of built-in functions for sorting arrays, including sort(), usort(), and ksort (). Each of these methods organizes the items of an array in a different way, and you may select the one that best meets your requirements.
This will sort the elements of the $fruits array in ascending alphabetical order.
Merging and Splicing Arrays
You can merge two or more arrays together using the array_merge() function, like so:
This will generate a new array containing all of the entries from $fruits1 and $fruits2. You may also use the array splice() method to delete entries from an array, as seen below:
This will remove the element at index 1 from the $fruits array.
Iterating Through Arrays
You can iterate through the elements of an array using a for loop or a foreach loop, like so:
Filtering Arrays
You can filter the elements of an array using the array_filter() function, like so:
This will create a new array that contains all elements of $fruits except for ‘banana’.
Working with Nested Arrays
Nested arrays are arrays that include one or more other arrays. They may be used to store sophisticated data structures.
Creating Nested Arrays
You can create a nested array by including an array as an element of another array. For example:
This creates an array $fruits with 3 elements
, where the third element is an array containing “orange” and “grapes”.
Accessing Elements in Nested Arrays
To access an element in a nested array, you must supply the element’s index or key at each level of the nested array. As an example:
Modifying Elements in Nested Arrays
You can modify an element in a nested array by specifying the index or key of the element in each level of the nested array. For example:
The value at index 0 of the third element (an array) of the $fruits array is changed from “orange” to “mango” in this example.
Iterating Through Nested Arrays
You can iterate through the elements of a nested array using nested loops. For example:
This will output all elements of the nested array $fruits.
Built-in PHP Array Functions
PHP has a number of built-in functions for working with arrays. The following are some of the most regularly utilized functions:
- count() : returns the number of elements in an array
- sort() : sorts the elements of an array
- implode() : converts an array into a string
- explode() : converts a string into an array
- array_keys() : returns all the keys of an array
- array_values() : returns all the values of an array
- array_unique() : removes duplicate values from an array
Best Practices for Working with PHP Arrays
- Choosing the right data type: It is important to choose the right data type for your array, as it can have a big impact on performance and memory usage.
- Optimizing performance: Avoid using large arrays or performing complex operations on them, as they can cause performance issues.
- Error handling and debugging: Always check for errors and debug your code when working with arrays.
- Security considerations: Be aware of potential security issues when working with arrays, such as SQL injection and cross-site scripting.
Real-world Examples of Using Arrays
- Data storage and retrieval from a database: Arrays are frequently used to store data retrieved from a database and then used to display it on a webpage.
- Developing a basic to-do list app: In a to-do list application, arrays may be used to store and manage a list of tasks.
- Creating a contact form: Arrays may be used to store and validate data sent via a contact form.
- Creating a simple shopping cart: Arrays can be used to store and manage the items in a shopping cart.
Q: What are the two main types of arrays in PHP?
A: The two main types of arrays in PHP are indexed arrays and associative arrays.
Q: How do you create an indexed array in PHP?
A: To create an indexed array in PHP, you can use the array() function or square brackets [] in PHP 5.4 and later versions. For example: $fruits = array(«apple», «banana», «orange»);
Q: How do you access an element in an indexed array?
A: To access an element in an indexed array, you can use the element’s index. For example: $fruits = array(«apple», «banana», «orange»); echo $fruits[0]; // outputs «apple»
Q: How do you create an associative array in PHP?
A: To create an associative array in PHP, you can use the array() function and assign keys to values. For example: $person = array(«name» => «John Smith», «age» => 30, «address» => «123 Main St.»);
Q: How do you access an element in an associative array?
A: To access an element in an associative array, you can use the element’s key. For example: $person = array(«name» => «John Smith», «age» => 30, «address» => «123 Main St.»); echo $person[«name»]; // outputs «John Smith»
Q: What is a nested array?
A: A nested array is an array that contains one or more arrays inside it. They are useful for storing complex data structures.
Q: How do you iterate through a nested array?
A: To iterate through a nested array, you can use nested loops. For example: foreach ($fruits as $fruit) < if (is_array($fruit)) < foreach ($fruit as $subFruit) < echo $subFruit; >> else < echo $fruit; >>
Q: What is the function to sort an array in PHP?
A: The built-in function to sort an array in PHP is sort() . For example: sort($fruits);
Q: What is the function to remove duplicates from an array in PHP?
A: The built-in function to remove duplicates from an array in PHP is array_unique() . For example: $unique = array_unique($fruits);
Q: What are some best practices to keep in mind when working with PHP arrays?
A: When dealing with PHP arrays, some best practices include selecting the appropriate data type, maximizing efficiency, managing errors and debugging, and being mindful of any security risks.
Как заполнить массив в php
I think your first, main example is needlessly confusing, very confusing to newbies:
It should be removed.
For newbies:
An array index can be any string value, even a value that is also a value in the array.
The value of array[«foo»] is «bar».
The value of array[«bar»] is «foo»
The following expressions are both true:
$array[«foo»] == «bar»
$array[«bar»] == «foo»
«If you convert a NULL value to an array, you get an empty array.»
This turns out to be a useful property. Say you have a search function that returns an array of values on success or NULL if nothing found.
<?php $values = search (. ); ?>
Now you want to merge the array with another array. What do we do if $values is NULL? No problem:
<?php $combined = array_merge ((array) $values , $other ); ?>
Voila.
Since PHP 7.1, the string will not be converted to array automatically.
Below codes will fail:
$a=array();
$a[‘a’]=»;
$a[‘a’][‘b’]=»;
//Warning: Illegal string offset ‘b’
//Warning: Cannot assign an empty string to a string offset
You have to change to as below:
$a[‘a’]=array(); // Declare it is an array first
$a[‘a’][‘b’]=»;
— quote —
Note:
Both square brackets and curly braces can be used interchangeably for accessing array elements
— quote end —
At least for php 5.4 and 5.6; if function returns an array, the curly brackets does not work directly accessing function result, eg. WillReturnArray() <1>. This will give «syntax error, unexpected ‘<' in. ".
Personally I use only square brackets, expect for accessing single char in string. Old habits.
Beware that if you’re using strings as indices in the $_POST array, that periods are transformed into underscores:
<html>
<body>
<?php
printf ( «POST: » ); print_r ( $_POST ); printf ( «<br/>» );
?>
<form method=»post» action default»><?php echo $_SERVER [ ‘PHP_SELF’ ]; ?> «>
<input type=»hidden» name=»Windows3.1″ value=»Sux»>
<input type=»submit» value=»Click» />
</form>
</body>
</html>
Once you click on the button, the page displays the following:
POST: Array ( [Windows3_1] => Sux )
Note that array value buckets are reference-safe, even through serialization.
<?php
$x = ‘initial’ ;
$test =array( ‘A’ =>& $x , ‘B’ =>& $x );
$test = unserialize ( serialize ( $test ));
$test [ ‘A’ ]= ‘changed’ ;
echo $test [ ‘B’ ]; // Outputs «changed»
?>
This can be useful in some cases, for example saving RAM within complex structures.
to know the depth (dimension) of a ARRAY, you can use this:
function Dim_Ar($A, $i) <
if(!is_array($A))return 0;
$t[] = 1;
foreach($A AS $e)if(is_array($e))$t[] = Dim_Ar($e, ++ $i) + 1;
return max($t);
>
$Q = ARRAY(ARRAY(ARRAY()), ARRAY(ARRAY()));// here depth/dimension is three
Regarding the previous comment, beware of the fact that reference to the last value of the array remains stored in $value after the foreach:
<?php
foreach ( $arr as $key => & $value )
<
$value = 1 ;
>
// without next line you can get bad results.
//unset( $value );
$value = 159 ;
?>
Now the last element of $arr has the value of ‘159’. If we remove the comment in the unset() line, everything works as expected ($arr has all values of ‘1’).
Bad results can also appear in nested foreach loops (the same reason as above).
So either unset $value after each foreach or better use the longer form:
//array keys are always integer and string data type and array values are all data type
//type casting and overwriting(data type of array key)
//—————————————————-
$arr = array(
1=>»a»,//int(1)
«3»=>»b»,//int(3)
«08»=>»c»,//string(2)»08″
«80»=>»d»,//int(80)
«0»=>»e»,//int(0)
«Hellow»=>»f»,//string(6)»Hellow»
«10Hellow»=>»h»,//string(8)»10Hellow»
1.5=>»j»,//int(1.5)
«1.5»=>»k»,//string(3)»1.5″
0.0=>»l»,//int(0)
false=>»m»,//int(false)
true=>»n»,//int(true)
«true»=>»o»,//string(4)»true»
«false»=>»p»,//string(5)»false»
null=>»q»,//string(0)»»
NULL=>»r»,//string(0)»» note null and NULL are same
«NULL»=>»s»,//string(4)»NULL» . In last element of multiline array,comma is better to used.
);
//check the data type name of key
foreach ($arr as $key => $value) <
var_dump($key);
echo «<br>»;
>
//NOte :array and object data type in keys are Illegal ofset.
[Editor’s note: You can achieve what you’re looking for by referencing $single, rather than copying it by value in your foreach statement. See http://php.net/foreach for more details.]
Don’t know if this is known or not, but it did eat some of my time and maybe it won’t eat your time now.
I tried to add something to a multidimensional array, but that didn’t work at first, look at the code below to see what I mean:
$a1 = array( «a» => 0 , «b» => 1 );
$a2 = array( «aa» => 00 , «bb» => 11 );
$together = array( $a1 , $a2 );
foreach( $together as $single ) <
$single [ «c» ] = 3 ;
>
foreach( $together as $key => $value ) <
$together [ $key ][ «c» ] = 3 ;
>
// Before php 5.4
$array = array(1,2,3);
// since php 5.4 , short syntax
$array = [1,2,3];
// I recommend using the short syntax if you have php version >= 5.4
Used to creating arrays like this in Perl?
Looks like we need the range() function in PHP:
<?php
$array = array_merge (array( ‘All’ ), range ( ‘A’ , ‘Z’ ));
?>
You don’t need to array_merge if it’s just one range:
There is another kind of array (php>= 5.3.0) produced by
$array = new SplFixedArray(5);
Standard arrays, as documented here, are marvellously flexible and, due to the underlying hashtable, extremely fast for certain kinds of lookup operation.
Supposing a large string-keyed array
$arr=[‘string1’=>$data1, ‘string2’=>$data2 etc. ]
when getting the keyed data with
php does *not* have to search through the array comparing each key string to the given key (‘string1’) one by one, which could take a long time with a large array. Instead the hashtable means that php takes the given key string and computes from it the memory location of the keyed data, and then instantly retrieves the data. Marvellous! And so quick. And no need to know anything about hashtables as it’s all hidden away.
However, there is a lot of overhead in that. It uses lots of memory, as hashtables tend to (also nearly doubling on a 64bit server), and should be significantly slower for integer keyed arrays than old-fashioned (non-hashtable) integer-keyed arrays. For that see more on SplFixedArray :
Unlike a standard php (hashtabled) array, if you lookup by integer then the integer itself denotes the memory location of the data, no hashtable computation on the integer key needed. This is much quicker. It’s also quicker to build the array compared to the complex operations needed for hashtables. And it uses a lot less memory as there is no hashtable data structure. This is really an optimisation decision, but in some cases of large integer keyed arrays it may significantly reduce server memory and increase performance (including the avoiding of expensive memory deallocation of hashtable arrays at the exiting of the script).
Function unset can delete array’s element by reference only when you specify source array. See example:
<?php
$array = [ 1 , 2 , 3 , 4 , 5 ];
foreach ( $array as $k => & $v ) <
if ( $k >= 3 ) <
unset( $v );
>
>
echo count ( $array ); // 5
?>
In this case unset delete only reference, however original array didn’t change.
Or different example:
<?php
$arr = [ 1 , 2 ];
$a = & $arr [ 0 ];
unset( $a );
count ( $arr ); // 2
?>
So for deleting element from first example need use key and array.
<?php
// .
unset( $array [ $k ]);
// .
?>
When creating arrays , if we have an element with the same value as another element from the same array, we would expect PHP instead of creating new zval container to increase the refcount and point the duplicate symbol to the same zval. This is true except for value type integer.
Example:
$arr = [‘bebe’ => ‘Bob’, ‘age’ => 23, ‘too’ => 23 ];
xdebug_debug_zval( ‘arr’ );
(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=0, is_ref=0)int 23
‘too’ => (refcount=0, is_ref=0)int 23
but :
$arr = [‘bebe’ => ‘Bob’, ‘age’ => 23, ‘too’ => ’23’ ];
xdebug_debug_zval( ‘arr’ );
(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=0, is_ref=0)int 23
‘too’ => (refcount=1, is_ref=0)string ’23’ (length=2)
or :
$arr = [‘bebe’ => ‘Bob’, ‘age’ => [1,2], ‘too’ => [1,2] ];
xdebug_debug_zval( ‘arr’ );
(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=2, is_ref=0)
array (size=2)
0 => (refcount=0, is_ref=0)int 1
1 => (refcount=0, is_ref=0)int 2
‘too’ => (refcount=2, is_ref=0)
array (size=2)
0 => (refcount=0, is_ref=0)int 1
1 => (refcount=0, is_ref=0)int 2