[wp-hackers] PHP Coding Practices

Evan Broder wp at ebroder.net
Wed Feb 15 00:45:10 GMT 2006


Mark Jaquith wrote:
> 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/
+1 on both counts. Adding those recommendations to the Codex coding 
practices page would be nice as well, at least the second one---I had 
never thought of casting the variables. My code has always used the if 
method.

- Evan


More information about the wp-hackers mailing list