Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

If I have the following variable in PHP:

$Message='Hello, this is just test message'; 

How can I get the size of its content in bytes? For instance, to print something like:

<p>Message size is 20KB</p> 
like image 913
Alaa Gamal Avatar asked Jul 06 '12 16:07

Alaa Gamal


People also ask

How to get text length in PHP?

The strlen() is a built-in function in PHP which returns the length of a given string. It takes a string as a parameter and returns its length. It calculates the length of the string including all the whitespaces and special characters.

What is $_ in PHP?

PHP $_GET is a PHP super global variable which is used to collect form data after submitting an HTML form with method="get". $_GET can also collect data sent in the URL. Assume we have an HTML page that contains a hyperlink with parameters: <html> <body>

Which function is used to detect how much memory the variable uses?

memory_get_usage() — Returns the amount of memory allocated to PHP.

How many values can a PHP variable hold?

php.net: The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18.


1 Answers

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"; 
like image 65
Mike Mackintosh Avatar answered Sep 19 '22 18:09

Mike Mackintosh