[pmwiki-users] Irreproducible behavior - maybe a bug

Joachim Durchholz jo at durchholz.org
Wed May 11 15:58:36 CDT 2005


Radu wrote:

> Are you sure you didn't mean
> 
> function to_array($a) {
>   if (is_array($a))
>     return $a;
>   else
>     return array($a);
> }

Let me explain a bit better:

I assume you meant to say

 >   if (is_array($a))
 >     return $a;
 >   else
 >     "somehow convert $a to an array"

PHP offers just one way to do that, with a type cast:

   (array) $a

It would be even easier to do it that way: a type cast does nothing if 
the value already has the right type, so the entire "if" statement could 
be replaced with

   return (array) $a;

which would make the entire function pointless - it's just as easy to write

   (array) something

as

   to_array(something)

and in fact PmWiki uses (array) in several places.

However, the PHP manual quite explicitly states that (array) is 
"undefined". In other words, it may do anything from "works as expected" 
to "starts a nuclear war". Typically, undefined behavior turns out to be 
roughly like what I described (though the exacty kind of behavior can 
vary wildly with PHP version).

For this reason, I proposed to avoid the (array) construct and replace 
it with the to_array function. That it returns an empty array is just 
what I think Patrick wanted the (array) type cast to do if the parameter 
value is not an array (typically, it would be a NULL).

A "safer" version of to_array would be

function to_array($a) {
   if (is_array($a))
     return $a;
   elseif isset($a)
     # not NULL, not an array: emit a warning
     return array();
     # oh, we could also return it as a one-element array
     # like you proposed:
     return array($a);
     # or
     return array(0 => $a);
   else
     return array();
}

Whether that's useful depends entirely on what Patrick assumed that 
(array) would do.

Regards,
Jo



More information about the pmwiki-users mailing list