Forum Moderators: coopster

Message Too Old, No Replies

string size in bytes

         

gliff

1:41 pm on Jul 28, 2005 (gmt 0)

10+ Year Member



I seem to be missing part of my brain today. Is there a built-in PHP function or language construct that will tell you the size of a particular variable in bytes? As in, I have a variable named $foo that contains the string “hi there”. I want to know how many bytes “hi there” takes up in memory.

Context

I’m forcing downloads by printing out strings, and would like a proper Content-Length header. If I wanted to get hackish, I know I could output the string to a temporary file and then use filesize() and readfile(), but I’d rather not go that route.

dcrombie

3:16 pm on Jul 28, 2005 (gmt 0)



Isn't 1 ASCII char === 1 byte?

gliff

3:52 pm on Jul 28, 2005 (gmt 0)

10+ Year Member



dcrombie, that all depends on the character encoding. One ASCII character takes one byte to store. However, if you're dealing with multi-byte strings and/or Unicode, one character doesn't necessarily correspond to one byte.

I am/was hoping there's a built-in function I've overlooked that automatically takes all that into account and magically spits out a number.

Thanks for the help though!

Mr_Fern

6:59 pm on Jul 28, 2005 (gmt 0)

10+ Year Member



[us3.php.net...]

This function might be helpful. Make sure to read the comment left on that page, it might help also.

ergophobe

12:25 am on Jul 29, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I guess by forcing mb_strlen() to treat the string as 'latin1' any multi-byte characters get treated as two characters (or more), so your count gets adjusted accordingly.

That's pretty smart.

gliff

2:22 pm on Jul 29, 2005 (gmt 0)

10+ Year Member



Tres useful Fern, thanks!