Php ограничить размер массива

Класс SplFixedArray

Класс SplFixedArray обеспечивает базовую функциональность, предоставляемую массивами. Главное различие между SplFixedArray и обычным массивом PHP в том, что размер SplFixedArray необходимо изменять вручную, а в качестве индексов могут выступать только целочисленные значения. Преимущество данных ограничений заключается в меньшем использовании памяти, чем стандартный массив ( array ).

Обзор классов

Список изменений

Версия Описание
8.1.0 Класс SplFixedArray теперь реализует интерфейс JsonSerializable .
8.0.0 Класс SplFixedArray теперь реализует интерфейс IteratorAggregate . Ранее был реализован интерфейс Iterator .

Примеры

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

// Инициализация массива фиксированной длиной
$array = new SplFixedArray ( 5 );

$array [ 1 ] = 2 ;
$array [ 4 ] = «foo» ;

var_dump ( $array [ 0 ]); // NULL
var_dump ( $array [ 1 ]); // int(2)

var_dump ( $array [ «4» ]); // string(3) «foo»

// Увеличение размера массива до 10
$array -> setSize ( 10 );

// Сокращаем размер массива до 2-х
$array -> setSize ( 2 );

// Следующий код вызывает исключение RuntimeException: Index invalid or out of range
try var_dump ( $array [ «non-numeric» ]);
> catch( RuntimeException $re ) echo «RuntimeException: » . $re -> getMessage (). «\n» ;
>

try var_dump ( $array [- 1 ]);
> catch( RuntimeException $re ) echo «RuntimeException: » . $re -> getMessage (). «\n» ;
>

try var_dump ( $array [ 5 ]);
> catch( RuntimeException $re ) echo «RuntimeException: » . $re -> getMessage (). «\n» ;
>
?>

Результат выполнения данного примера:

NULL int(2) string(3) "foo" RuntimeException: Index invalid or out of range RuntimeException: Index invalid or out of range RuntimeException: Index invalid or out of range

User Contributed Notes 8 notes

As the documentation says, SplFixedArray is meant to be *faster* than array. Do not blindly believe other people’s benchmarks, and beextra careful with the user comments on php.net. For instance, nairbv’s benchmark code is completely wrong. Among other errors, it intends to increase the size of the arrays, but always initialize a 20 elements SplFixedArray.

On a PHP 5.4 64 bits linux server, I found SplFixedArray to be always faster than array().
* small data (1,000):
* write: SplFixedArray is 15 % faster
* read: SplFixedArray is 5 % faster
* larger data (512,000):
* write: SplFixedArray is 33 % faster
* read: SplFixedArray is 10 % faster

Memory usage for arrays of 1132766 ints (data derived from some 1kx1k img):
Regular: 76453160B (67.5B/int)
SplFixed: 18898744B (16.7B/int)

In my application, SFA uses 75% less RAM, which is a life-saver.

Speed comparison:
Regular: 449ms
SplFixed (resized before every element): 791ms
SplFixed (fully preallocated): 392ms
SplFixed (preall-d to 1M and then resized): 547ms

Pros and cons:
+ much more efficient RAM-wise
+ a bit faster if max size is known
~ a bit slower if max size is only approximated
— much slower if max size is not known
— cannot be used with most array functions

To sum up:
SplFixedArray is a very good choice for storing giant amount of data, though only as long as you at least roughly know the size and can work without array functions.

Note, that this is considerably faster and should be used when the size of the array is known. Here are some very basic bench marks:

for( $size = 1000 ; $size < 50000000 ; $size *= 2 ) <
echo PHP_EOL . «Testing size: $size » . PHP_EOL ;
for( $s = microtime ( true ), $container = Array(), $i = 0 ; $i < $size ; $i ++) $container [ $i ] = NULL ;
echo «Array(): » . ( microtime ( true ) — $s ) . PHP_EOL ;

for( $s = microtime ( true ), $container = new SplFixedArray ( $size ), $i = 0 ; $i < $size ; $i ++) $container [ $i ] = NULL ;
echo «SplArray(): » . ( microtime ( true ) — $s ) . PHP_EOL ;
>
?>

OUTPUT
Testing size: 1000
Array(): 0.00046396255493164
SplArray(): 0.00023293495178223

Testing size: 2000
Array(): 0.00057101249694824
SplArray(): 0.0003058910369873

Testing size: 4000
Array(): 0.0015869140625
SplArray(): 0.00086307525634766

Testing size: 8000
Array(): 0.0024251937866211
SplArray(): 0.00211501121521

Testing size: 16000
Array(): 0.0057680606842041
SplArray(): 0.0041120052337646

Testing size: 32000
Array(): 0.011334896087646
SplArray(): 0.007631778717041

Testing size: 64000
Array(): 0.021990060806274
SplArray(): 0.013560056686401

Testing size: 128000
Array(): 0.053267002105713
SplArray(): 0.030976057052612

Testing size: 256000
Array(): 0.10280108451843
SplArray(): 0.056283950805664

Testing size: 512000
Array(): 0.20657992362976
SplArray(): 0.11510300636292

Testing size: 1024000
Array(): 0.4138810634613
SplArray(): 0.21826505661011

Testing size: 2048000
Array(): 0.85640096664429
SplArray(): 0.46247816085815

Testing size: 4096000
Array(): 1.7242450714111
SplArray(): 0.95304894447327

Testing size: 8192000
Array(): 3.448086977005
SplArray(): 1.96746301651

Memory footprint of splFixedArray is about 37% of a regular «array» of the same size.
I was hoping for more, but that’s also significant, and that’s where you should expect to see difference, not in «performance».

Be warned that SplFixedArray does not provide all of the main functionalities of array. For example, it does not support array_slice. SplFixedArray should be far more efficient at supporting such array operations than normal arrays (since it should be simply a contiguous slice). Check that all your main array functions are really supported before trying to use SplFixedArray instead of array. With JIT in PHP8, some loops to polyfill these are perhaps now realistic, but still not as fast as native functions.

PHP Arrays are very fast, and faster overall, especially in PHP7. You almost never need this. There are some cases where using this is better than using arrays but beware that they aren’t that obvious.

Note that (as of PHP 7.1) SplFixedArray uses 16 bytes (!) per array item. This can be checked easily via:

ini_set ( ‘memory_limit’ , ‘4M’ );
$array = new SplFixedArray ( 1000000 );
//PHP Fatal error: Allowed memory size of 4194304 bytes exhausted (tried to allocate 16000000 bytes)
?>

So if you’re considering SplFixedArray because you need to use large arrays with very large numbers of items, make sure you have enough memory to support them.

Источник

array_pad

array_pad() returns a copy of the array padded to size specified by length with value value . If length is positive then the array is padded on the right, if it’s negative then on the left. If the absolute value of length is less than or equal to the length of the array then no padding takes place. It is possible to add at most 1048576 elements at a time.

Parameters

Initial array of values to pad.

Value to pad if array is less than length .

Return Values

Returns a copy of the array padded to size specified by length with value value . If length is positive then the array is padded on the right, if it’s negative then on the left. If the absolute value of length is less than or equal to the length of the array then no padding takes place.

Examples

Example #1 array_pad() example

$result = array_pad ( $input , 5 , 0 );
// result is array(12, 10, 9, 0, 0)

$result = array_pad ( $input , — 7 , — 1 );
// result is array(-1, -1, -1, -1, 12, 10, 9)

$result = array_pad ( $input , 2 , «noop» );
// not padded
?>

See Also

User Contributed Notes 11 notes

Beware, if you try to pad an associative array using numeric keys, your keys will be re-numbered.

$a = array( ‘size’ => ‘large’ , ‘number’ => 20 , ‘color’ => ‘red’ );
print_r ( $a );
print_r ( array_pad ( $a , 5 , ‘foo’ ));

// use timestamps as keys
$b = array( 1229600459 => ‘large’ , 1229604787 => 20 , 1229609459 => ‘red’ );
print_r ( $b );
print_r ( array_pad ( $b , 5 , ‘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
)

Источник

Ограничение размера массива в PHP

Я задаюсь вопросом, существует ли ограничение размера для массива в php 5? Я написал сценарий php, чтобы изменить последний элемент каждой строки в файле. распечатайте содержимое измененного файла , когда я запускаю скрипт в файле небольшого размера (т.е. каждая строка содержит 4 значения), он будет работать. Когда я запускаю его в более крупном файле (например, 60000 строк, каждый из которых содержит 90 значений), он не изменяет бит исходного файла, но сценарий не выдавал никакого сообщения об исключении во время выполнения. Что это за проблема?

Solutions Collecting From Web of «Ограничение размера массива в PHP»

У вас может быть нехватка памяти, так как размер вашего массива (теоретически) ограничен только объемом памяти, выделенной для скрипта. Поместите ini_set(‘memory_limit’, ‘1024M’); в начале вашего скрипта установить ограничение на 1 ГБ. Возможно, вам понадобится увеличить это еще выше для достижения наилучших результатов.

Поскольку manyxcxi говорит, что вам, вероятно, придется увеличить memory_limit. Иногда вы также можете уменьшить использование памяти, отключив большие переменные с unset ($ var). Это необходимо только тогда, когда переменная остается в области далеко за ее последней точкой использования.

Вы случайно читаете весь файл, транслируете его, а затем записываете новый файл? Если это так, вы можете уменьшить использование памяти, работая в цикле, где вы читаете небольшую часть, обрабатываете ее и записываете и повторяете, пока не дойдете до конца файла. Но только если алгоритму преобразования не нужен весь файл, чтобы преобразовать небольшую часть.

  • Почему .htaccess перенаправляет URL-адрес маршрутизации, но разрывает ссылки css / js / image после двух уровней в глубину?
  • Как получить последний вставленный идентификатор таблицы MySQL в PHP?
  • Как я могу разобрать JSON-файл с PHP?
  • PHP: преобразовать строку пары значений, разделенных запятыми, в массив
  • Настройка нескольких языков wordpress
  • Категории и подкатегории с php, mysql и smarty
  • В чем разница между find () findOrFail () first () firstOrFail
  • Пользовательские сообщения об исключении: лучшие практики
  • Добавьте заголовок к каждому запросу с использованием .htaccess
  • Предупреждение: mysql_num_rows () ожидает, что параметр 1 будет ресурсом, массив указан в
  • Как продолжить процесс после ответа на запрос ajax в PHP?
  • Добавление нескольких конфигурационных массивов в PhalconPHP
  • Проблема PHP Phar – file_exists ()
  • Подтверждение страны / города / штата
  • Дата чтения человеком с использованием PHP

Источник

Читайте также:  What is php storm
Оцените статью