0

I have a multidimensional array. If it contains less than a threshold $threshold = 1000 bits/bytes/anything of data in total, including it's keys, I want to fetch more content.

What is the cheapest way, performance/memory wise, to get an approximate of the array size?

Right now, I use strlen(serialize($array)). Updated as per the comments:

$threshold = 1000;
$myArray = array(
    'size' => 0,
    'items' => array(
        ['id' => 1, 'content' => 'Lorem ipsum'],
        ['id' => 2, 'content' => 'Dolor sit'],
        ['id' => 3, 'content' => 'Amet']
    )
);

while($myArray['size'] < $threshold)
{
    echo "Array size is below threshold.<br/>";
    addStuffToArray($myArray);
}

function addStuffToArray(&$arr)
{
     echo "Adding stuff to array.<br/>";
     $newArrayItem = array(
         'id' => rand(0, 10000),
         'content' => rand(999999, 999999)
     );
     $arr['size'] += strlen(serialize($newArrayItem));
     $arr['items'][] = $newArrayItem;
}

PHPFiddle here.

Rein
  • 1,347
  • 3
  • 17
  • 26
  • 1
    what is wrong with your current code? It works perfectly when its about the amount of the characters... _If it contains less than a threshold $threshold = 1000 bits/bytes/anything of data in total_ But you can't compare apple and oranges.... – B001ᛦ Sep 13 '18 at 13:39
  • That's true! I figured that, most of the time when I find a solution, there are much cheaper/quicker ways to achieve the same result. As this is part of code that will be ran many times, the cheaper it can be done, the better. – Rein Sep 13 '18 at 13:44
  • 1
    Do you want exact data size *excluding key lengths and serialisation construct* or including everything, json_encode would give better performance and less meta? – Lawrence Cherone Sep 13 '18 at 13:44
  • That's a great idea. I'm not interested in exact data size, I want a ballpark notion of how big the array is. Performance is much more important than exact size. I'll give json_encode a try. I also found this https://stackoverflow.com/questions/804045/preferred-method-to-store-php-arrays-json-encode-vs-serialize – Rein Sep 13 '18 at 13:49
  • https://stackoverflow.com/questions/1351855/getting-size-in-memory-of-an-object-in-php – Alex Sep 13 '18 at 13:51
  • 1
    Also instead of doing it after the fact, you might as well do it in `addStuffToArray` and just keep track of the data being put into the array and in the while loop look at that value instead. – Lawrence Cherone Sep 13 '18 at 13:54
  • @LawrenceCherone that's very clever, this way I don't have to re-serialize the entire array every loop. Thanks! – Rein Sep 13 '18 at 14:01

1 Answers1

-2

You could always just count:

$count = array_map('count', $myArray);

This will give you an array with the count of all the sub-arrays. However, the way you have done it is not bad.