Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If i start an array in PHP with nth index how much memory it will occupy?

Tags:

arrays

php

I need to create an array in Php by using index as nth number. For instance:

<?php
    $A = array();
    $A['1000']='Some value';

Does this array will occupy memory for remaining 999 indexes?

like image 782
Rahat Hameed Avatar asked Jan 26 '23 07:01

Rahat Hameed


1 Answers

An array in php associates values to keys. It is like an ordered map as you can find in the official documentation.

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.

This means that php won't allocate memory for the remaining 999 indexes. Also, you can test it by converting the array to json:

echo json_encode($A);

This will return

{"1000":"Some value"}
like image 88
Hichem BOUSSETTA Avatar answered Jan 29 '23 14:01

Hichem BOUSSETTA