3

Just browsing over the latest release of the PHP coding standards, and something caught my eye:

http://svn.php.net/viewvc/php/php-src/trunk/CODING_STANDARDS?revision=296679&view=markup

Coding standard #4 states that "When writing functions that deal with strings, be sure to remember that PHP holds the length property of each string, and that it shouldn't be calculated with strlen()..."

I've ALWAYS used strlen, and maybe it's just late, but how do you access the built-in length property of a string in PHP?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Unpossible
  • 10,607
  • 22
  • 75
  • 113

3 Answers3

10

They're talking about the C function, not the PHP function. The C function will stop counting after the first \0, but PHP strings can contain \0 elsewhere other than the end.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • Damn, why'd you edit? Thought I'd be able to add something else as well. Oh well, have a +1 :) – alex Nov 12 '10 at 05:54
  • It seems to me like this recommendation is talking specifically about PHP... the preamble states "This file lists several standards that any programmer, adding or changing code in PHP, should follow." and then lists this as one of those things, no mention of C until further down in the syntax section... and they SPECIFICALLY mention not to use strlen in PHP. Strange. – Unpossible Nov 12 '10 at 14:35
  • After digging through the PHP source, you are indeed correct, it appears they are referring to the C function. – Unpossible Sep 17 '11 at 22:54
1

Its been clearly mentioned that they talking about PHP Coding standards not about C function or extension of PHP engines.

========================
PHP Coding Standards
========================
This file lists several standards that any programmer, adding or changing code in PHP, should follow. Since this file was added at a very late stage of the development of PHP v3.0, the code base does not (yet) fully follow it, but it's going in that general direction. Since we are now well into the version 4 releases, many sections have been recoded to use these rules.

Still I didn't found any relevant information about string length property but I think in future they might release the information if it's related to new version of PHP.

Please post if someone found useful information about this.

0

To get the length of a string zval (variable in C) use Z_STRLEN(your_zval) see zend_operators.h at line 398 (PHP 5.4) :

#define Z_STRLEN(zval)          (zval).value.str.len
John Conde
  • 217,595
  • 99
  • 455
  • 496
zenko
  • 1