Hello! There is a function that returns a 3-dimensional array, which contains 2 submasives, one 2-dimensional and one simple. Next, the array is displayed under the corresponding HTML template. To do this, I need to extract the subarrays into separate variables, and I know 4 options:

  1. $ subArray1 = $ bigArray ['subArray1']; $ subArray2 = $ bigArray ['subArray2'];

  2. list ($ subArray1, $ subArray2) = $ bigArray;

  3. $ subArray2 = array_pop ($ bigArray); $ subArray1 = array_pop ($ bigArray);

  4. $ subArray1 = array_shift ($ bigArray); $ subArray2 = array_shift ($ bigArray);

I asked myself what is the best in terms of performance and whether there is an alternative way to access each sub-array of a large array by reference.

  • so it is not clear) you can dump the array and what do you want to get from it? - Ale_x
  • I could not use such a complex array if I knew that such a piece of code would work: function getRow () {... $ row = mysql_query ($ query); $ row ['uniqueKey'] = 'some text data'; return $ row; } - Sergey Pnicnik
  • The naked eye suggests that the first version is the most productive. - ReinRaus
  • It seems to me that in the first version we double the amount of memory: a large array remains, and in addition to it, 2 new variables are created that together occupy as much memory as a large array - Sergey Picnik

1 answer 1

The first option is perhaps the best in this case. Memory consumption does not increase much, because PHP actually copies the array only at the moment when you change at least one element.

list() is just a complication of the first.

array_pop() and array_shift() also change the array.

You can experiment:

 // массив $a = array(); for ($i = 0; $i<600; $i++) { $a[0][$i] = str_repeat('Первый', 50); $a[1][$i] = str_repeat('Второй', 50); for ($j = 0; $j<3; $j++) { $a[0][$i][$j] = str_repeat('йывреП', 30); $a[1][$i][$j] = str_repeat('йоротВ', 30); } } // и проверка for ($i = 0; $i<100; $i++) { // list(${'f'.$i}, ${'s'.$i}) = $a; // ${'f'.$i} = $a[0]; // ${'s'.$i} = $a[1]; // ${'f'.$i} = array_pop($a); // ${'s'.$i} = array_pop($a); // ${'f'.$i} = array_shift($a); // ${'s'.$i} = array_shift($a); // Эксперимент с памятью: // раскомментировать первую строку, запустить -> посмотреть потребление памяти, // раскомментировать вторую -> посмотреть как потребление выросло в несколько раз // ${'tmp'.$i} = $a; // ${'tmp'.$i}[0][10][5] = 'Новый'; } 

I didn’t have anything to do ..