[wp-hackers] PHP Coding Practices

Mark Jaquith mark.wordpress at txfx.net
Wed Feb 15 00:19:38 GMT 2006


I'd like to get some group feedback on this:

Issue #1

WP currently uses strstr() in many places just to establish basic  
"this string exists in that string" functionality.  According to  
http://php.net/strstr, "Note:  If you only want to determine if a  
particular needle  occurs within haystack, use the faster and less  
memory intensive function strpos() instead."

And, of course, when using strpos(), you have to be careful to check  
it with === or !== against boolean false.  if ( strpos($haystack,  
$needle) !== false ) { // $needle exists in $haystack }

I made this change in one of my recent "Massive Code Cleanups" but  
would like to know if it would be worth changing all other instances  
for speed/consistency/code-is-poetry.


Issue #2

We've gotten into trouble several times with running foreach() on  
something that might not be an array.  We currently are using a lot  
of "if ( !empty($things) )" checks to prevent that.  I'm rather a fan  
of casting to array when using foreach:

foreach ( (array) $things as $thing ) {

If $things is null or false or whatever, it just becomes an empty  
array, and the foreach block gets skipped... the desired behavior.   
It's less code, and it brings all foreach() loop up a level in terms  
of code indentation, which increases readability.

--
Mark Jaquith
http://txfx.net/




More information about the wp-hackers mailing list