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.