How to get the size of the content of a variable in PHP

$start_memory = memory_get_usage();
$foo = "Some variable";
echo memory_get_usage() - $start_memory;

This is good if you are working with any type of var.


strlen returns the number of bytes in the string, not the character length. View the PHP Manual here.

Look closely at:

Note:

strlen() returns the number of bytes rather than the number of characters in a string.

If you take the result and multiple by 8, you can get bits.

Here is a function which can easily do the math for you.

function strbits($string){
    return (strlen($string)*8);
}

Note, if you use, memory_get_usage(), you will have the wrong value returned. Memory get usage is the amount of memory allocated by the PHP script. This means, within its parser, it is allocating memory for the string and the value of the string. As a result, the value of this before and after setting a var, would be higher than expected.

Example, the string: Hello, this is just test message, produces the following values:

Memory (non-real): 344 bytes
Strlen: 32 Bytes
Strlen * 8bits: 256 bits

Here is the code:

<?php
$mem1 = memory_get_usage();
$a = 'Hello, this is just test message';

echo "Memory (non-real): ". (memory_get_usage() - $mem1)."\n";
echo "Strlen: ". strlen($a)."\n";
echo "Strlen * 8bits: ". (strlen($a) * 8)."\n";

Tags:

Php